How to use findAll() in yii2?

孤街醉人 提交于 2019-12-12 17:16:54

问题


I want to know how can i get all data of user with array id for where condition

In yii you could do something like this

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

or

$userDtls = Student::model ()->findAllByAttributes ( array (
                    'id' => explode ( ",", $_POST ['studentIds'] ) 
            ) );

Now in yii2 CDbCriteria is not there, so which approach should i use to achieve same thing??

I have tried this but it only returns data for first id in the array

$result = Users::findAll([ 'id'=> $_POST ['keylist']]);

In documentation it is written that we can use this

$result = Users::findAll([1,488,489]);

But my array $_POST['keylist'] is something like this

keylist{
   0='1'
   1='5'
   2='8'
}

I have also tried this

$ids = \Yii::$app->request->post('keylist', []);

$result = Users::findAll($ids);

And still returns data for first id in the array here is the screenshot

Thats why it doesnt work i guess

thank you


回答1:


$users = Users::findAll($ids); is a correct approach.

See what you can pass in $ids in official docs here.

As I explained you here, you should never trust data from $_POST and check it for existence and validate before using.

Example of getting and check for existence with Yii2:

$ids = \Yii::$app->request->post('ids');

Or just:

$ids = isset($_POST['ids']) ? $_POST['ids'] : null;

For more complex cases I'd recommend to create separate search model and use it with validation, see Gii's CRUD for example.

UPDATE: Pay attention to what you actually pass as $ids.




回答2:


$students_ids = Yii::$app->request->post('studentIds');
if(isset($students_ids)) {
     $result = Users::find()->where(['in','id',$students_ids])->all();
}

var_dump($result)

Try like this



来源:https://stackoverflow.com/questions/32856991/how-to-use-findall-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!