[英]Placing a where clause at end of SQL statement using codeigniter's active record
我正在嘗試使用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`
注意我添加的括號
要使用活動記錄執行此操作,您將需要將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();
讓我知道這項工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.