【问题标题】:Associative array turned into where OR clause in Codeigniter关联数组变成了 Codeigniter 中的 where OR 子句
【发布时间】:2015-08-31 21:46:29
【问题描述】:

使用 CI,我尝试使用三个参数设置查询:user_id、content_type 和 content_id,其中 content_id 是 ID 数组。

所以我需要做这样的事情:

SELECT name FROM content WHERE user_id = 2 AND content_type = file AND (content_id = 4 OR content_id = 5 OR content_id = 7 ...).
  1. 问题:获取所有 content_id 的查询是否正确?
  2. CI有什么我可以说的功能吗

        $this->db->select('name');
        $this->db->from('content');
        $this->db->where('user_id', $user_id);
        $this->db->where('content_ids', $content_ids);
        $this->db->where('content_type', $content_type);
    

    只是这样中间的 where 子句实际上是在其间嵌套 OR 并填充关联数组 ($content_ids) 的地方?

感谢您的回答。

编辑:我找到了一个解决方案:where_in 命令完全符合我的需要。

【问题讨论】:

  • 好的,我刚刚从 CI 中发现了 where_in 子句。这是正确的方向吗?
  • 是的,你的做法是正确的
  • 对于使用where_or OP 需要使用loop 而不是where_in 将在没有循环@saty 的情况下做到这一点
  • 是的,我知道那是你,我删除了我的评论。
  • 我已经发布了我的答案@Novocaine。 为了完整起见

标签: php mysql codeigniter associative-array


【解决方案1】:

你可以使用IN子句替换很多OR条件

所以您在 Active Records 中的查询看起来像

$content_ids = array(4,5,7);
$where = array('user_id' => $user_id,'content_type' => $content_type);
$this->db->select('name');
$this->db->from('content');
$this->db->where($where);//created array of where clause
$this->db->where_in('content_type', $content_ids);
return $this->db->get()->result_array();

【讨论】:

  • 你确定你必须内爆 content_ids 吗?在手册页上有一个纯数组使用..
  • 是的,您可以直接在 implode 中使用该数组,感谢您指出 @SubjectX。即使我也更新了我的答案
猜你喜欢
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
相关资源
最近更新 更多