2012-02-06 90 views
1

我要做到以下幾點:多ActiveRecord的查詢CI中

//set up insert.... 
$this->db->insert('property'); 
$id = $this->db->insert_id(); 
//some stuff 
//set up get 
$this->db->where('id', $id); 
$id = $this->db->get(); 

這是行不通的。它會出現插入沒有被執行之前得到 - 獲取返回零行。該插入確實(最終)工作。有什麼建議麼?

+0

這顯然不理想(插入然後閱讀),但它大大簡化了我的代碼。可能有更好的方法,但我沒有精力去解決它。現在更令人惱火的是我缺乏對上述不起作用的理解。 – Jack 2012-02-06 19:16:52

+1

你可能想檢查你的數據庫內容 - 當它錯誤時,調用'$ this-> db-> last_query()' - 將返回最新的查詢,這樣你就可以看到你創建的查詢。 – uzsolt 2012-02-06 20:37:55

+0

爲什麼插入然後閱讀簡化代碼?如果你插入一行,你爲什麼需要閱讀?您是否已經擁有要插入的數據? – 2012-02-06 20:40:56

回答

2

你錯過了一個參數 - insert()有兩個:

  1. 表名
  2. 數組或對象包含列和值

From the documentation

$data = array(
    'title' => 'My title' , 
    'name' => 'My Name' , 
    'date' => 'My date' 
); 

$this->db->insert('mytable', $data); 

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date') 

所以,你需要提供insert()通過包含一個數組或對象作爲第二個參數來獲得必要的數據

編輯:

或者,你可以使用$this->db->set()方法設置值,如Rocket's more comprehensive answer解釋的,你需要的也指出指定的表中選擇數據時。

2

您需要給insert插入一些數據。

不管是用set方法:

$this->db->set('name', 'Eric'); 
$this->db->insert('property'); 

或通過傳遞一個數組作爲第二個參數:

$this->db->insert('property', array(
    'name' => 'Eric' 
)); 

至於,你的選擇,你需要告訴它從選擇什麼樣的表。

使用任一方法from

$this->db->from('property'); 
$this->db->where('id', $id); 
$id = $this->db->get(); 

或通過get一個表作爲一個參數:

$this->db->where('id', $id); 
$id = $this->db->get('property'); 

此外,請注意get()返回查詢對象。您需要使用->row(或->result)來獲取數據。

$this->db->from('property'); 
$this->db->where('id', $id); 
$query = $this->db->get(); 
$id = $query->row()->id;