如何在 findAll 中使用“IN (1,2,3)"? [英] How to use 'IN (1,2,3)' with findAll?

查看:27
本文介绍了如何在 findAll 中使用“IN (1,2,3)"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从数据库中获取几个学生,并且我将它们的主键放在逗号分隔的字符串中.

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

通常使用 SQL 应该是这样的:

Normally using SQL it would be something like:

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

Yii 的 ActiveRecord 似乎在结果 SQL 语句中的绑定参数周围插入了一个单引号,这导致使用参数绑定时查询失败.

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?

推荐答案

你也可以这样做:

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

并在数组中使用您需要的任何值.

and use in array any values you need.

阿列克谢

这篇关于如何在 findAll 中使用“IN (1,2,3)"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆