Yii2 - ActiveRecord to Array

后端 未结 3 1943
情歌与酒
情歌与酒 2021-01-01 11:03

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(

相关标签:
3条回答
  • 2021-01-01 11:25

    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);
            },
        ],
    ]);
    
    0 讨论(0)
  • 2021-01-01 11:30

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

    $User = User::find()->one();
    $user_as_array = $User->attributes;
    
    0 讨论(0)
  • 2021-01-01 11:37

    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();
    
    0 讨论(0)
提交回复
热议问题