使用 CodeIgniter 查询生成器方法将 WHERE 子句条件的部分括在括号中

发布于 2024-10-15 23:07:09 字数 845 浏览 1 评论 0原文

我有以下代码:

$this->db->from('addresses');
$this->db->where('user_id', $this->session->userdata('user.id'));
$this->db->like('country',    $pSearch); 
$this->db->or_like('state',   $pSearch); 
$this->db->or_like('city',    $pSearch); 
$this->db->or_like('zip',    $pSearch); 

生成以下 SQL

SELECT *
FROM (`addresses`)
WHERE `user_id` = '1'
AND  `country`  LIKE '%d%'
OR  `state`  LIKE '%d%'
OR  `city`  LIKE '%d%'
OR  `zip`  LIKE '%d%'
ORDER BY `country` asc
LIMIT 15

有没有办法让它像这样生成:

SELECT *
FROM (`addresses`)
WHERE `user_id` = '1'
AND  (`country`  LIKE '%d%'
OR  `state`  LIKE '%d%'
OR  `city`  LIKE '%d%'
OR  `zip`  LIKE '%d%')
ORDER BY `country` asc
LIMIT 15

因为我只想获取 user_id = 1 的记录,而不是所有用户的记录。

I have the following code:

$this->db->from('addresses');
$this->db->where('user_id', $this->session->userdata('user.id'));
$this->db->like('country',    $pSearch); 
$this->db->or_like('state',   $pSearch); 
$this->db->or_like('city',    $pSearch); 
$this->db->or_like('zip',    $pSearch); 

which generates the following SQL

SELECT *
FROM (`addresses`)
WHERE `user_id` = '1'
AND  `country`  LIKE '%d%'
OR  `state`  LIKE '%d%'
OR  `city`  LIKE '%d%'
OR  `zip`  LIKE '%d%'
ORDER BY `country` asc
LIMIT 15

Is there a way to make it generate it like this:

SELECT *
FROM (`addresses`)
WHERE `user_id` = '1'
AND  (`country`  LIKE '%d%'
OR  `state`  LIKE '%d%'
OR  `city`  LIKE '%d%'
OR  `zip`  LIKE '%d%')
ORDER BY `country` asc
LIMIT 15

As I want to get only the records for user_id = 1 and not for all users.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我恋#小黄人 2024-10-22 23:07:09

这似乎是 CI ActiveRecord 中的错误/限制。您可以尝试 Ignited Query,它能够处理嵌套的 WHERE 子句,并且可能可以按照您喜欢的方式处理嵌套的 WHERE/LIKE

查看此帖子以获取更多信息。

That seems to be a bug/limitation in CI ActiveRecord. You could try Ignited Query, which has the ability to handle nested WHERE clauses, and probably can handle the nested WHERE/LIKE the way you like.

Check out this thread also for more info.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文