【问题标题】:Using CakePHP to insert rows into a table with one IDENTITY column only使用 CakePHP 将行插入到只有一个 IDENTITY 列的表中
【发布时间】:2014-02-17 19:57:09
【问题描述】:

在现有的帖子(下面的链接)中,我已经知道如何将一行插入到具有 Microsoft SQL Server 的一个标识列的表中。

Inserting rows into a table with one IDENTITY column only

现在我想使用 CakePHP 来做同样的事情。但是,当我尝试以下操作时,记录将不会被保存。

$this -> MyModel -> create();
if ($this -> MyModel -> save()) {
    $this -> log('Record is saved', 'debug');
} else {
    // Always run the following
    $this -> log('Record is not saved', 'debug');
}

将这样的记录保存到表中的 CakePHP 方法是什么?

MyModel 的表架构如下:

CREATE TABLE [dbo].[my_models] (
    [id] INT NOT NULL PRIMARY KEY IDENTITY
)

【问题讨论】:

  • 这似乎是在 CakePHP 中保存的正确方法,虽然,我看不出你在保存什么。您没有将任何内容传递到您的保存方法/操作中,例如$this->MyModel->save($this->request->data);。也就是说,数据是否以这种方式传递给模型。
  • MyModel 的架构是什么?这取决于该架构。
  • @AKKA-Web 谢谢。实际上,唯一要保存的数据是身份列的值,我希望它由数据库自动分配。您可以在我上面编辑的帖子中查看上面的表架构。
  • @Anubhav 感谢您的提醒。我在上面编辑的帖子中包含了架构。
  • 将 [id] 列的属性更改为 [id] INT NOT NULL PRIMARY KEY UNIQUE AUTO_INCREMENT,您的代码是正确的。

标签: sql sql-server tsql cakephp cakephp-2.4


【解决方案1】:

出于演示目的,当前模型写为“__THE_CURRENT_MODEL__”,当然,不是正确的 CakePHP 模型名称。 呃!

    public function add() {
        if( $this->request->is('post') ){
            $this->__THE_CURRENT_MODEL__->create();
            if( $this->__THE_CURRENT_MODEL__->save(
                array(
                    '__THE_CURRENT_MODEL__' => array( 'id' => 'NULL' )
                )
            ) ){
                $this->Flash->success(__('The __current_model__ has been saved.'));
                return $this->redirect( array( 'action' => 'index' ) );
            }else{
                $this->Flash->error(__('The __current_model__ could not be saved. Please, try again.'));
            }
        }
    }

您应该注意 - 'NULL' 值不是 NULL .. 这将导致根本没有查询 - id 列数字

【讨论】:

  • 我无法再访问该环境,我懒得从头开始设置一个来测试它。无论如何,我仍然会将其标记为答案。
【解决方案2】:

这就是我最终编写代码的方式。除了创建的行之外,这还检索标识列的生成值。我更喜欢使用$this -> MyModel -> save();,但由于我不知道该怎么做,所以我只能使用直接 SQL 执行来归档结果。

如果有人可以建议一种方法来回答我的问题$this -> MyModel -> save();,我很乐意将其标记为答案。

注意:SQL 可能无法在某些旧版本的 MS SQL Server 上运行。

$sql = 'INSERT INTO ' . $this -> MyModel -> table . ' OUTPUT INSERTED.' . $this -> MyModel -> primaryKey . ' DEFAULT VALUES;';
$dbh = $this -> MyModel -> getDataSource() -> getConnection();
$stmt = $dbh -> prepare($sql);
$stmt -> execute();
$sqlResult = $stmt -> fetch(PDO::FETCH_NUM);
$stmt -> closeCursor();

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2010-11-24
    • 2011-05-06
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多