有没有办法将ActiveRecord
转换为Yii2中的数组?我知道我们可以为ActiveQuery
执行此操作,例如User::find()->asArray()->one();
,但是当它已经被提取时我们可以将Model
转换为数组吗?我希望在beforeSave()
方法中执行此操作,并将该数组存储在缓存中。
答案 0 :(得分:38)
从Yii2 guide - 使用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);
},
],
]);
答案 1 :(得分:37)
试试这个!
$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();
答案 2 :(得分:3)
对于一个模型,使用属性attributes
$User = User::find()->one();
$user_as_array = $User->attributes;