有没有办法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)
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)
对于一个模型来说,使用一个属性就足够了attributes
$User = User::find()->one();
$user_as_array = $User->attributes;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41329 次 |
| 最近记录: |