-->

How to use findAll() in yii2?

2019-07-11 06:39发布

问题:

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