Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - ActiveRecord to Array

Tags:

yii2

Is there any way to convert ActiveRecord to an array in Yii2? I do know we can do that for ActiveQuery, for example User::find()->asArray()->one();, but can we convert Model to array when it is already fetched? I want to do that in beforeSave() method and store that array in cache.

like image 776
Volodymyr Avatar asked Jun 29 '15 20:06

Volodymyr


People also ask

What is ActiveRecord in Yii2?

Active Record provides an object-oriented API for accessing data. An Active Record class is associated with a database table. Yii provides the Active Record support for the following relational databases − MySQL 4.1 or later.

What is active query in yii?

An ActiveQuery can be a normal query or be used in a relational context. ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().


1 Answers

Try this!

$model = Post::find($id)->limit(10)->asArray()->all(); $model = Post::find($id)->select('id,name as full')->asArray()->one(); $model = Post::find($id)->select('id,name as full')->asArray()->all(); $model = Post::find()->where(['slug'=>$slug])->asArray()->one(); 
like image 87
Muhammad Shahzad Avatar answered Nov 05 '22 18:11

Muhammad Shahzad