簡體   English   中英

使用codeigniter的活動記錄在SQL語句末尾放置where子句

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM