How to use 'IN (1,2,3)' with findAll?

2019-04-03 09:50发布

I need to get a couple of Students from the database, and I have their primary keys in a comma-separated string.

Normally using SQL it would be something like:

$cleanedStudentIdStringList = "1,2,3,4";
SELECT * FROM Student WHERE id IN ($cleanedStudentIdStringList)

Yii's ActiveRecord seems to insert a single quote around bound parameters in the resulting SQL statement which cause the query to fail when using parameter binding.

This works, but doesn't use safe parameter binding.

$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");

Is there a way to still use parameter binding and get only a couple of rows in a single query?

2条回答
三岁会撩人
2楼-- · 2019-04-03 10:48

You can do it also that way:

$criteria = new CDbCriteria();
$criteria->addInCondition("id", array(1,2,3,4));
$result = Student::model()->findAll($criteria);

and use in array any values you need.

Aleksy

查看更多
戒情不戒烟
3楼-- · 2019-04-03 10:49

You can use findAllByAttributes method also:

$a=array(1,2,3,4);
$model = Student::model()->findAllByAttributes(array("id"=>$a));
查看更多
登录 后发表回答