2011-03-03 68 views
2

我想将数组传递给有查询的模型。我不知道如何正确地传递数组,或者如果我必须以某种方式操作数组。codeigniter传递数组以查询

我有这样的阵列:

Array 
(
    [0] => 1 
    [1] => 2 
) 

我有此线的控制器:

$ratings = $this->login_model->get_ratings($mechanicIds); // get the mechanic ratings 

我有这样的模型:

function get_ratings($mechanicId) 
    { 
     $sql = "select m.mechanic_id, 
        m.mechanic_name, 
        m.city, 
        m.state, 
        count(mr.rating_id) as num_ratings, 
        round(avg(mr.rating_id),2) avg_rating 
       from mechanic m, mechanic_rating mr, rating r 
       where m.mechanic_id in (?) 
       and m.mechanic_id = mr.mechanic_id 
       and mr.rating_id = r.rating_id"; 

     $query = $this->db->query($sql, $mechanicId); 

     if($query->num_rows() > 0) 
     { 
      return $query->result_array(); 
     } 
     else 
     { 
      return false; 
     } 
    } 

它实际上返回的结果,但问题是它只返回结果1行,当它应该返回2,因为我的数组中有2个结果。任何人都知道我做错了什么?

+0

数组中的元素,都被用于WHERE在查询条款? – kushalbhaktajoshi 2011-03-03 02:37:11

+0

是的,我试图使用他们的行“在哪里m.mechanic在(?)” – Catfish 2011-03-03 21:44:25

回答

2

我发现这个问题,这帮助。

下面是我使用的代码。

控制器包含这样的:其含有本

   $mIds_size = count($mIds); 
       $i = 1; 

       foreach($mIds as $row) 
       { 
        if($i == $mIds_size) 
        { 
         $mechanicIds .= $row; 
        } 
        else 
        { 
         $mechanicIds .= $row.', '; 
        } 
        $i++; 
       } 

       $ratings = $this->login_model->get_ratings($mechanicIds); // get the mechanic ratings 

型号:

function get_ratings($mechanicId) 
    { 

     $this->db->escape($mechanicId); 

     $sql = "select m.mechanic_id, 
         m.mechanic_name, 
         m.city, 
         m.state, 
         count(mr.rating_id) as num_ratings, 
         round(avg(mr.rating_id),2) avg_rating 
       from mechanic m, mechanic_rating mr, rating r 
       where m.mechanic_id in ($mechanicId) 
       and m.mechanic_id = mr.mechanic_id 
       and mr.rating_id = r.rating_id 
       group by mechanic_id"; 

     $query = $this->db->query($sql, $mechanicId); 

     if($query->num_rows() > 0) 
     { 
      return $query->result_array(); 
     } 
     else 
     { 
      return false; 
     } 
    } 
+2

的文档中的“查询绑定”部分您的foreach循环完全等同于'implode(',',$ mIds);' – jfoucher 2012-08-06 20:14:17

+0

这是一个较老的问题,所以它在我的脑海中并不新鲜,你读了评论给你的答案?它不起作用,因为它将所有元素组合在一起的单引号。 – Catfish 2012-08-06 22:45:15

+0

据我所知,Codeigniter可能会自动转义它传递的值。 – jfoucher 2012-08-07 07:16:11

1

改变这一行:

$query = $this->db->query($sql, $mechanicId); 

这样:

$query = $this->db->query($sql, array(implode(', ',$mechanicId))); 

the manual

+0

我有这一点,但它只返回一个结果。玩过你的答案后,我意识到这是因为我没有在我的查询中的group by子句。谢谢你的帮助。 – Catfish 2011-03-03 23:05:35

+0

好吧,我猜这是行不通的。当我使用“在哪里m.mechanic(1,2)”在mysql中运行查询时,我得到2行。当我在我的程序中尝试相同的查询时,除了我使用“其中m.mechanic在(?)”中的行,它只给出了1个结果。 – Catfish 2011-03-03 23:12:17

+0

从查看文档,我敢打赌,它期待另一个问号来使用数组中的第二个元素。 – Catfish 2011-03-03 23:16:22