如何将MySQL查询转换为codeigniter活动记录?

时间:2014-12-19 08:11:13

标签: mysql codeigniter

我是codeigniter的新手,我想将以下MySQL查询转换为Codeigniter Active Record Queries。

MySQL查询:

select sevadar_id, sevadar_name from tbl_sevadarmaster where  
sevadar_designation = 6 and sevadar_id not in (SELECT p_id FROM  
`tbl_events` WHERE program_id = 27 and event_date = 2014-07-06 and p_id is not null)

1 个答案:

答案 0 :(得分:0)

CodeIgniter为他们的整个API提供了非常好的文档我强烈建议他们快速阅读。特别是关于您的问题,您应该查看Active Record文档here和CodeIgniter query library,它将为您提供使用API​​生成更安全查询的提示。这两个链接一起包含您在CodeIgniter中构建查询所需的所有API调用。

在最简单的层面上你可以做到:

$query = $this->db->query('select sevadar_id, sevadar_name from tbl_sevadarmaster where sevadar_designation = 6 and sevadar_id not in (SELECT p_id FROM `tbl_events` WHERE program_id = 27 and event_date = 2014-07-06 and p_id is not null)');

但是您想要使用查询绑定(请参阅query libraries页面的最底部)来自动转义数据以生成更安全的查询,这里是使用该页面的查询绑定的示例API:

$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?"; 
$this->db->query($sql, array(3, 'live', 'Rick'));

如果您使用Active Record库,您可以尝试:

$this->db->select('p_id');
$this->db->from('tbl_events');
$this->db->where('program_id', 27);
$this->db->where('event_date', '2014-07-06');
$this->db->where('p_id is not', null);
$where_clause = $this->db->get_compiled_select();

$this->db->select('sevadar_id, sevadar_name');
$this->db->from('tbl_sevadarmaster');
$this->db->where('sevadar_designation', 6);
$this->db->where("`sevadar_id` NOT IN ($where_clause)", NULL, FALSE);