Yii2 - ActiveRecord 到数组 [英] Yii2 - ActiveRecord to Array
本文介绍了Yii2 - ActiveRecord 到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有什么方法可以将 ActiveRecord
转换为 Yii2 中的数组?我知道我们可以为 ActiveQuery
做到这一点,例如 User::find()->asArray()->one();
,但我们可以转换Model
已经获取到数组?我想在 beforeSave()
方法中做到这一点,并将该数组存储在缓存中.
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.
推荐答案
来自 Yii2 指南 - 使用 ArrayHelper::toArray()
:
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);
},
],
]);
这篇关于Yii2 - ActiveRecord 到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文