php - 使用 codeigniter 的事件记录在 SQL 语句末尾放置 where 子句

标签 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 语句之后?

最佳答案

试试这个:

$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` 

注意我添加的括号

要使用事件记录执行此操作,您需要将字符串传递给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();

让我知道这是否有效

关于php - 使用 codeigniter 的事件记录在 SQL 语句末尾放置 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793188/

相关文章:

php - 如何在mRender中使用条件: datatables php mysql

php - 干净的 URL

php - Laravel,在 Eloquent 语法中应用 where 之后 with

mysql - 跨两列的唯一约束

SQL 字符串替换通配符

mysql - 用重复字段的总和更新 table1 的列

PHP 图像处理。棕褐色、饱和度、 toastr 滤镜与 CSS 中的完全相同

Php, MySql - 将数据作为键值对插入到两个表中

mysql - 在mysql数据库中随机获取特定实体的记录

mysql - 查询没有像预期的那样工作