【问题标题】:Is there a way to insert a row with no data有没有办法插入没有数据的行
【发布时间】:2016-08-17 03:38:03
【问题描述】:

使用 CakePHP 3.3,我有一个只包含主键的表。这被用作一个序列。在 CakePHP 中,我插入一个没有数据的行并生成一个新行。

蛋糕 2.7

class Identity extends AppModel {

    function nextVal() {
        $data = [];
        $this->create();
        $this->save($data);
        return $this->id;
    }
}

我试图在 CakePHP 3.3 中复制这种行为,但它并没有达到我的预期。

CakePHP 3.3

class IdentityTable extends Table
{
    public function generate() {
        $identity = $this->newEntity();
        if ( $this->save($identity) ) {
            // The $ccn entity contains the id now
            \Cake\Log\Log::debug(__METHOD__. ' success');
            return $identity->id;
        }
        \Cake\Log\Log::debug(__METHOD__. ' failed');
        return false;
    }
    //
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('identity');
        $this->displayField('identityId');
        $this->primaryKey('identityId');
    }
}

MySQL 对此非常满意:

INSERT INTO `identity` () VALUES()

我在想 CakePHP 3.x ORM 看到我没有插入任何东西,它会在保存时放弃。

CakePHP 3 中有没有办法插入没有数据的行?

【问题讨论】:

    标签: mysql cakephp cakephp-3.0


    【解决方案1】:

    您必须告诉 cake 实体中存在某些内容并将其标记为“脏”。即

    $identity ->dirty('id', true);
    

    所以结果查询将是

    INSERT INTO sic_suppliers (id) VALUES (NULL)
    

    我猜你没问题

    PS 不知道这是否是实现这一目标的最佳方法,但它似乎有效。

    编辑:按照@ndm的建议你也可以直接插入记录(见cookbook

    $this->query()->insert(['id'])
        ->values([null])
        ->execute();
    

    【讨论】:

    • 它可能会起作用,因为对于这样的空实体没有应用程序规则会失败,即可能需要将checkRules 设置为false。另一种选择可能是 insert the record directly
    • @ndm,但您似乎无法将空数组传递给 insert 方法,因此您必须以某种方式告诉 cake 其中一个字段为空。无论如何,我会根据您的建议编辑我的答案。
    • @ndm 还可以如何检索插入实体的 id?
    • 没错,您必须至少传递一个字段,并且将null 传递为主键应该可以正常工作IIRC。插入 ID 可以通过 execute() 返回的语句对象上的 lastInsertId() 方法检索。但是,这比保存一个空实体要多得多,为了完整起见,我刚刚提到它;)
    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2012-12-10
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多