15

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

3 Answers 3

23

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Is this correct (perhaps the question should be 'still' correct)? If I CTRL click on find() in my IDE, it says it does not take any parameters. Cannot find any examples with a parameter either. yiiframework.com/doc/api/2.0/yii-db-activerecord#find()-detail yiiframework.com/doc/api/2.0/yii-db-activequery
You are right, @johnsnails . This answer should't be accepted, 'cause right way is: Customer::find()->where(['id' => $id])->asArray()->one();.
16

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();

Comments

2

you may use

$model = Customer::findModel($id);
$model->attributes;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.