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.
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.
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().
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With