使用 CodeIgniter Active Record 语句
Posted
技术标签:
【中文标题】使用 CodeIgniter Active Record 语句【英文标题】:Using CodeIgniter Active Record statements 【发布时间】:2013-04-11 18:09:43 【问题描述】:我正在寻找一种在 CodeIgniter 中使用 Active Record 来构建我的查询的方法。
我当前的代码是这样的:
$this->db-> like('responsible', $user->id);
$this->db->or_like('accountable', $user->id);
$this->db->or_like('consulted', $user->id);
$this->db->or_like('informed', $user->id);
// Get the tasks, but only with the correct start or end date
$tasks = $this->db->get_where('level_' . $this->config->item('answer_level'), array('date_end' => $offset, 'ccode' => $user->country));
// Check if tasks exist
if($tasks->num_rows() > 0)
// Tasks have been found that should have been finished!
echo $tasks->num_rows() . " tasks found for " . $user->first_name . " that should have been finished!\n";
$last_month_tasks = $tasks->result();
unset($tasks);
这会产生以下 SQL:
SELECT *
FROM (`level_3`)
WHERE `date_start` = -5
AND `ccode` = 'GB'
AND `responsible` LIKE '%5%'
OR `accountable` LIKE '%5%'
OR `consulted` LIKE '%5%'
OR `informed` LIKE '%5%'
但我需要它来生成这个 SQL:
SELECT *
FROM (`level_3`)
WHERE `date_start` = -5
AND `ccode` = 'GB'
AND (
`responsible` LIKE '%5%'
OR `accountable` LIKE '%5%'
OR `consulted` LIKE '%5%'
OR `informed` LIKE '%5%'
)
【问题讨论】:
【参考方案1】:CodeIgniter 的 ActiveRecord 不支持查询和子句的嵌套。 你必须像这样手动完成:
$this->db->select('*');
$this->db->from('level_' . $this->config->item('answer_level'));
$this->db->where(array('date_end' => $offset, 'ccode' => $user->country));
$this->db->where("(responsible LIKE '%5%' OR accountable LIKE '%5%' OR consulted LIKE '%5%' OR informed LIKE '%5%')");
$tasks = $this->db->get();
【讨论】:
谢谢,我将编辑 SQL 以修复您回答中的一些问题。以上是关于使用 CodeIgniter Active Record 语句的主要内容,如果未能解决你的问题,请参考以下文章
CodeIgniter Active Record 与常规查询
使用 CodeIgniter 中的 Active Record 类从 4 个表中选择数据
Codeigniter Active Record使用多个主键选择多行