2016-08-17 84 views
0

使用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的ORM 3.x的看到,我不插入任何东西,它想逃的保存。

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

回答

0

你必须告诉蛋糕,在实体中存在某些事物并将其标记为“脏”。即

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

所以结果查询将

INSERT INTO sic_suppliers (id) VALUES (NULL) 

,我的猜测是对你合适

PS 不知道这是否是实现这一目标的最佳途径,但它似乎上班。

编辑:以下@ndm建议您也可以直接插入记录(见cookbook

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

它可以工作,因为没有将失败的这样一个空的实体应用程序规则,即可能有必要将'checkRules'设置为'false'。另一种选择可能是** [直接插入记录](http://book.cakephp.org/3.0/en/orm/query-builder.html#inserting-data)** – ndm

+0

@ndm,但似乎你不能将一个空数组传递给插入方法,所以在某种程度上你必须告诉蛋糕其中一个字段为空。无论如何,我会根据您的建议编辑我的答案。 – arilia

+0

@ndm还可以如何检索插入的实体的ID? – arilia