【问题标题】:How to use where_in using Active Record Codeigniter?如何通过 Active Record Codeigniter 使用 where_in?
【发布时间】:2016-03-05 07:50:28
【问题描述】:

我想使用 Active Record 将数组传递给 where_in。

我看到的参考链接很少,可以这样传递:

$this->db->where_in('id', array('20','15','22','42','86'));

查询:

$mts = $this->db->select('subcat_id')->get_where('subcategory_tbl', array('cat_id' => $cat_id));
$result = $mts->result_array();

但我的结果数组是这种形式的:

Array
(
    [0] => Array
        (
            [subcat_id] => 12
        )

    [1] => Array
        (
            [subcat_id] => 13
        )
)

那么我怎样才能将这个数组 id 传递给 where_in 子句呢?我在这里很困惑。

【问题讨论】:

    标签: php codeigniter activerecord


    【解决方案1】:

    你可以这样做:

    $this->db->where_in('cat_id', $cat_id)
    $this->db->select('subcat_id');
    $this->db->get('subcategory_tbl');
    

    假设 $cat_id 包含要检查的值数组。

    【讨论】:

      【解决方案2】:
      $names = array('Frank', 'Todd', 'James');
      $this->db->where_in('username', $names);
      

      【讨论】:

        【解决方案3】:

        您需要将结果(行数组)转换为这些行的第一个“列”中的值数组:

        $ids = array_map(function($row) { return $row['subcat_id']; }, $result);
        

        您可能应该在使用之前检查 $ids 是否为空 - 因为(我不记得但我认为)where_in 会很乐意生成无效的

        SELECT ... WHERE id IN ()

        如果你传递一个空数组。

        【讨论】:

          【解决方案4】:

          使用你的第一个查询

          $mts = $this->db->select('GROUP_CONCAT(subcat_id) as new')->get_where('subcategory_tbl', array('cat_id' => $cat_id))->row()->new;
          

          然后使用

          if($mts != "")
          {
              $this->db->where_in('id',  $mts);
          }
          

          希望对你有帮助....

          【讨论】:

          • 不会 ->row()->subcat_id 只获取 first 行的 subcat_id?
          • @ShadowRadiance 我在这里使用GROUP_CONCAT... :)
          • 我完全错过了 GROUP_CONCAT ......您是否仍然需要分解 $mts 才能将数组传递给 where_in 或者它会处理这样的字符串?
          • 另外......如果没有匹配会发生什么......你需要一个警卫,这样它就不会生成“WHERE id IN ()”(从技术上讲,我的回答会出现问题还有...我会记下)
          • 是的 IN () 也像这样工作 IN (x,y,z).... 是的,他需要确保它不是空白的 :)
          猜你喜欢
          • 1970-01-01
          • 2013-04-11
          • 2011-11-18
          • 2012-03-24
          • 1970-01-01
          • 2011-10-23
          • 2012-06-05
          • 1970-01-01
          • 2013-02-18
          相关资源
          最近更新 更多