createCommand(..._yii where in">
赞
踩
代码如下: public function test(){
$a = array(1,2,3,4,5);
$uid = implode(',', $a);
$sql = "SELECT A.uid,B.id,B.state FROM A
LEFT JOIN B ON A.id=B.id
WHERE A.uid in ($uid)";
$cmd =
Self::getDb()->createCommand($sql);
$res =
$cmd->queryAll();
/*var_dump($res);
array (size=3)
0 =>
array (size=6)
'uid' => string '1' (length=2)
'id' => string '1100' (length=5)
'state' => string '2' (length=1)
1 =>
array (size=6)
'uid' => string '2' (length=2)
'id' => string '1200' (length=5)
'state' => string '2' (length=1)
2 =>
array (size=6)
'uid' => string '3' (length=2)
'id' => string '1300' (length=5)
'state' => string '2' (length=1)*/
//-----------------------------绑定参数法-----------------------------------------
$sql2 = "SELECT A.uid,B.id,B.state FROM A
LEFT JOIN B ON A.id=B.id
WHERE A.uid in (:uid)";
$cmd2 =
Self::getDb()->createCommand($sql2);
$cmd2 -> bindParam(":uid",$uid);
$res2 =
$cmd2->queryAll();
/*var_dump($res2);
array (size=3)
0 =>
array (size=6)
'uid' => string '1' (length=2)
'id' => string '1100' (length=5)
'state' => string '2' (length=1)*/}假如$sql得到的结果有三条数据,用$sql2得到的结果只有一条数据(经测试,调换$a里元素的位置发现,$res2的数据一直是$a里第一个有数据的元素所对应的那条数据)。经过测试和了解,发现bindParam会在替换占位符时会在参数外边加一个单引号,这样我的in条件里边就变成了一个整体,而不是五个值。问题:1.就算作为一个整体,为什么还会得到一条数据呢。2.本题怎么改正3.YII2里,如果要使用占位符,where条件要用到in时,应该怎么使用, 抱歉这么晚来补充,楼上两位给的链接都挺有用的。 yii2 里联表查询时有join,joinWith这两种用法,还有其他用法,我在解决in的问题的时候用的是join这种用法: $array 是一个数组 A model: self::find()->select(['A.sort','A.id','count(B.id) ct','B.id','B.state'])->join('LEFT JOIN','Btable B','B.fid=A.id')->where('in','A.id',$array)->asArray()->all(); 仅供参考,如有其他用法,请慷慨分享 , 请使用 Yii2 提供的AR直接操作,请参考 http://www.yiiframework.com/doc-2.0/guide-db-active-record.html, http://stackoverflow.com/questions/14767530/php-using-pdo-with-in-clause-array, $placeholders = str_repeat('?,', count($ids) - 1). '?'; $command = \Yii::$app->db->createCommand("select id,chepai from car WHERE id IN (".$placeholders.")");foreach($ids as $i => $id){
$command->bindValue($i+1,$id);}return $command->queryAll();$params = [];$sql = \Yii::$app->db->getQueryBuilder()->buildCondition(['IN', 'id', $ids], $params);foreach ($ids as $key => $val){
$params[':qp'.$key] = $val;}$command = \Yii::$app->db->createCommand("select id,chepai from car
WHERE $sql", $params);return $command->queryAll();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。