2012-02-06 34 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;