【问题标题】:Codeigniter combines the query inside a loopCodeigniter 将查询组合在一个循环中
【发布时间】:2019-09-24 15:02:13
【问题描述】:

我有一个 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;
}

这是该代码的结果,使用分析器。

我的身份证是

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;
}

输出:空数组。

【问题讨论】:

  • @danblack 我用您的解决方案编辑了代码,但仍然,codeigniter 仍在添加那些 where 子句。
  • danblack 的解决方案只要您没有循环使用它就可以工作。

标签: php mysql sql codeigniter


【解决方案1】:

我不知道这是 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;
}

【讨论】:

    【解决方案2】:

    试试这个,

    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();
          }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 2018-07-15
      相关资源
      最近更新 更多