Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 findModel to Array

Tags:

yii2

In the yii2 documentation I found there is a way to convert active record to array .

Customer::find()->asArray()->all();

But I can't use like this :-

Customer::findModel($id)->asArray();

How should I do? Please help

like image 450
Chhorn Soro Avatar asked Jan 08 '15 06:01

Chhorn Soro


3 Answers

You should add asArray() to ActiveQuery, not to the instance of ActiveRecord. Assuming your primary key column named id, you should change your model finding code to:

Customer::find(['id' => $id])->asArray()->one();
like image 99
arogachev Avatar answered Nov 15 '22 16:11

arogachev


Whole model as array

$model = Customer::find($id)->asArray()->one();

Select specific columns

 $model = Customer::find($id)->select('id,name')->asArray()->one();

Select specific columns as alias

$model = Customer::find($id)->select('id,name as full')->asArray()->one();

Where condition

$model = Customer::find()->where(['email'=>$email])->asArray()->one();

Whole records?

$model = Customer::find($id)->asArray()->all();
like image 32
Muhammad Shahzad Avatar answered Nov 15 '22 16:11

Muhammad Shahzad


you may use

$model = Customer::findModel($id);
$model->attributes;
like image 1
andika Avatar answered Nov 15 '22 15:11

andika