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.
Asked
Active
Viewed 5.3k times
28
3 Answers
52
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();
![](../../users/profiles/2138791.webp)
Muhammad Shahzad
- 7,778
- 20
- 71
- 123
-
2this is a more yii2 way – sasori Feb 13 '17 at 15:21
-
1This answer is far more optimal – dzona Mar 21 '17 at 16:41
-
3TS noted: _But can we convert Model to Array **when it is already fetched**_. So, that answer is not very useful. – Boolean_Type Nov 17 '17 at 10:44
-
1this should have been the selected answer – Reborn Feb 05 '18 at 16:03
-
This doesn't answer the question, and this information was already in the question. – Coz Dec 13 '18 at 16:19
-
This did not answer the question, yet was very helpfull. – Harijs Krūtainis Mar 04 '19 at 09:43
48
From Yii2 guide - use ArrayHelper::toArray()
:
$posts = Post::find()->limit(10)->all();
$data = ArrayHelper::toArray($posts, [
'app\models\Post' => [
'id',
'title',
// the key name in array result => property name
'createTime' => 'created_at',
// the key name in array result => anonymous function
'length' => function ($post) {
return strlen($post->content);
},
],
]);
-
9I would like to add that ActiveRecord also has a function `toArray()`, so `$model->toArray()` would also work for converting a single model after it is fetched. – Jelmer Keij Apr 11 '16 at 09:26
-
@JelmerKeij please post a proper related question well described so all the SO community can help you .. and eventually comment me with the link of this question .. – scaisEdge Apr 11 '16 at 09:33
-
3Hi @scaisEdge it's not a question, it's extra information to point out that there's also the function `toArray()` you can use. – Jelmer Keij Apr 12 '16 at 10:26
-
@JelmerKeij yes i kwon is function of activeRecord http://www.yiiframework.com/doc-2.0/yii-db-activerecord.html – scaisEdge Apr 12 '16 at 10:57
3
For one model it's sufficient to use a property attributes
$User = User::find()->one();
$user_as_array = $User->attributes;
![](../../users/profiles/1538898.webp)
German Khokhlov
- 909
- 9
- 13
-
1Thank you! I'm new in Yii2, and it's a few difficult to make chains like `$model->search($request->get())->getModels()[0]->attributes` for example, for debug. Becouse all works via magic methods and IDE can't help. – Aleksej_Shherbak Jul 28 '20 at 09:54