使用codeigniter的活动记录在SQL语句的末尾放置一个where子句

时间:2014-04-01 17:49:24

标签: php mysql sql codeigniter activerecord

我尝试使用codeingniter的活动记录创建SQL语句,类似于:

SELECT *
FROM (`posts`)
JOIN `Post_images` ON `Post_images`.`post_id` = `posts`.`id`
WHERE `title`  LIKE '% $SEARCHTERM %'
OR  `content`  LIKE '% $SEARCHTERM %'
AND `location` =  ' $LOCATION '
GROUP BY `posts`.`id` 

我的PHP目前:

$this->db->like('title', $term);

$this->db->or_like('content', $term);

$this->db->group_by('posts.id');

$this->db->join('Post_images', 'Post_images.post_id = posts.id');

$query = $this->db->get_where('posts', array('location' => $location));

return $query->result_array();

这个PHP生成的查询是:

SELECT *
FROM (`posts`)
JOIN `Post_images` ON `Post_images`.`post_id` = `posts`.`id`
WHERE `location` =  ' $LOCATION '
AND  `title`  LIKE '% $SEARCHTERM %'
OR  `content`  LIKE '% $SEARCHTERM %'
GROUP BY `posts`.`id` 

如果在“内容”中找到匹配项,那么OR语句就在最后。列完全忽略该位置。

是否有确保在WHERE声明之后放置OR声明?

1 个答案:

答案 0 :(得分:0)

试试这个:

$this->db->like('title', $term);
$this->db->or_like('content', $term);
$this->db->where('location = ', $location);
$this->db->group_by('posts.id');
$this->db->join('Post_images', 'Post_images.post_id = posts.id');
$query = $this->db->get('posts');

return $query->result_array();

这将重现您的预期查询,但我认为您希望这样的工作正常工作:

SELECT *
FROM (`posts`)
JOIN `Post_images` ON `Post_images`.`post_id` = `posts`.`id`
WHERE (`title`  LIKE '% $SEARCHTERM %'
OR  `content`  LIKE '% $SEARCHTERM %')
AND `location` =  ' $LOCATION '
GROUP BY `posts`.`id` 

注意我添加的括号

要使用活动记录执行此操作,您需要将string传递给where方法,如下所示:

$this->db->where("(`title` LIKE '% $term %' || `content` LIKE '% $term %')");
$this->db->where('location = ', $location);
$this->db->group_by('posts.id');
$this->db->join('Post_images', 'Post_images.post_id = posts.id');
$query = $this->db->get('posts');

return $query->result_array();

让我知道这项工作是否