I want to do a findAll and get all of the IDs into an array.
What is the best way to do this, I notice Yii 2 has an asArray() method and a toArray() method, is it possible to do it using these? If so, can you show me how?
I know how to do it via findAll records manually and then running a foreach loop etc and creating a new array from it but I am not looking for that.
I am looking for the best way to do it.
I think ArrayHelper::map is what you are looking for.
there are a lot of nice array helpers take a look at this:
// in your model function:
$query = static::find()->orderBy('attribute_1 ASC')->all();
return ArrayHelper::map($query, 'attribute_1', 'attribute_2');
you should receive an array like:
'attribute_1_value_1' => 'attribute_2_value_1',
'attribute_1_value_2' => 'attribute_2_value_2',
'attribute_1_value_3' => 'attribute_2_value_3',
Hope this helps.
There’s also a method in
ActiveQuery for directly achieving this:
$ids = User::find()->select('id')->column();