2016-08-17 83 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