Yii2 - ActiveRecord到Array

Vol*_*myr 18 yii2

有没有办法ActiveRecord在Yii2中转换为数组?我知道我们可以做到这一点ActiveQuery,例如User::find()->asArray()->one();,但是Model当它已经被提取时我们可以转换为数组吗?我想在beforeSave()方法中执行该操作并将该数组存储在缓存中.

sca*_*dge 42

来自Yii2 指南 - 使用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);
        },
    ],
]);
Run Code Online (Sandbox Code Playgroud)

  • 我想补充一点,ActiveRecord也有一个函数`toArray()`,所以`$ model-> toArray()`也适用于在获取后转换单个模型. (9认同)
  • 嗨@scaisEdge这不是一个问题,它是额外的信息,指出你还可以使用函数`toArray()`. (3认同)

Muh*_*zad 41

试试这个!

$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();
Run Code Online (Sandbox Code Playgroud)

  • TS注意到:_但是当我们已经获取**_时,我们可以将模型转换为数组**.所以,这个答案并不是很有用. (3认同)
  • 这是更多的方式 (2认同)

Ger*_*lov 6

对于一个模型来说,使用一个属性就足够了attributes

$User = User::find()->one();
$user_as_array = $User->attributes;
Run Code Online (Sandbox Code Playgroud)