Yii2 - ActiveRecord to Array

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

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

Tags:

Yii2