2014-01-27 142 views
0

在現有的文章中(下面的鏈接)我已經知道如何將行插入到具有Microsoft SQL Server的一個標識列的表中。使用CakePHP將行插入到只有一個IDENTITY列的表中

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 
) 
+0

這似乎是保存在CakePHP中的正確方法,但是,我沒有看到你正在保存的內容。你不會傳遞任何東西到你的save方法/動作中,比如'$ this-> MyModel-> save($ this-> request-> data);'。那就是如果數據以這種方式傳遞給模型。 –

+0

什麼是MyModel的模式?它取決於該模式。 – Anubhav

+0

@ AKKA-Web謝謝。實際上唯一要保存的數據是我希望它由數據庫自動分配的標識列的值。你可以在我上面編輯過的文章中查看上面的表格模式。 – VCD

回答

0

出於演示的目的當前模型寫入爲「__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列數字

+0

我無法再訪問環境,我懶得從頭設置一個來測試它。無論如何,我仍然會將此標記爲答案。 – VCD

0

這是我在我的代碼結束了。除了創建的行之外,它還檢索標識列的生成值。我寧願使用$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(); 
相關問題