Yii2 - ActiveRecord to Array

三世轮回 提交于 2020-05-10 07:01:28

问题


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.


回答1:


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);
        },
    ],
]);



回答2:


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



回答3:


For one model it's enough to use a property attributes

$User = User::find()->one();
$user_as_array = $User->attributes;


来源:https://stackoverflow.com/questions/31125334/yii2-activerecord-to-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!