Codeigniter在循环内组合查询

时间:2019-05-07 01:21:08

标签: php mysql sql codeigniter

我有一个ID数组,我正在从数据库中获取这些项的详细信息。我创建了一个foreach循环来逐个获取每个项目,然后将其推入数组,然后返回到控制器。问题是查询构建器将所有ID合并到一个查询中。

public function get_product_by_ids($ids) {
        $products = array();
        foreach ($ids as $id) {
            $this->db->where('product_id', $id);
            $query = $this->db->get('products')->row_array();

            array_push($products, $query);
        }

    return $products;
}

这是使用探查器的代码的结果。

我的ID是

Array
(
    [0] => 22
    [1] => 18
    [2] => 21
)

探查器产生的查询:

SELECT *
FROM `products`
WHERE `product_id` = '22'
AND `product_id` = '18'
AND `product_id` = '21'
AND `product_id` = '22' 

SELECT *
FROM `products`
WHERE `product_id` = '18' 

SELECT *
FROM `products`
WHERE `product_id` = '21' 

输出: 第一个是空的,然后我得到了第二个,直到最后一个。

我尝试使用where_in()就像@danblack所说的,这是产生的查询:

SELECT *
FROM `products`
WHERE `product_id` = '22'
AND `product_id` = '18'
AND `product_id` = '21'
AND `product_id` IN('22', '18', '21') 

这是我的新代码:

public function get_product_by_ids($ids) {
        $this->db->where_in('product_id', $ids);
        $query = $this->db->get('products')->result_array();

        return $query;
}

输出:空数组。

2 个答案:

答案 0 :(得分:0)

我不知道这是CodeIgniter(在Codeigniter 3.x上)是否有问题,或者我做错了什么,但这是我的临时解决方案:

public function get_product_by_ids($ids) {
        $newquery = "SELECT * FROM products WHERE product_id IN(";

        $counter = 0;
        foreach ($ids as $id) {
            $newquery .= "'".$id."'";
            if($counter < (sizeof($ids) - 1)) {
                $newquery .= ", ";
            }
            $counter++;
        }

        $newquery .= ")";
        $query = $this->db->query($newquery)->result_array();

        return $query;
}

答案 1 :(得分:0)

尝试一下

public function get_product_by_ids($ids) {
      $this->db->select('*');
      $this->db->from('products');
      $this->db->where_in('product_id', $ids);//$ids should be array
      $query = $this->db->get();
      if ($query->num_rows() > 0) {
         return $query->result_array();
      }else{
         return array();
      }
}