yii2.如何在dataProvider中设置场景? [英] Yii2. How to set scenario in dataProvider?

查看:36
本文介绍了yii2.如何在dataProvider中设置场景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据场景返回不同的字段.如何在 dataProvider 中设置它?

I want to return different fields depends on scenario. How can I set it in dataProvider?

$query = User::find();
$activeData = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
     ],
]);

用户模型中的字段:

public function fields()
{
    if ($this->scenario == 'statistics') {
        return [
            'id',
            'email',
            'count'
        ];
    }
    return [
        'id',
        'name'
    ];
}

推荐答案

只需使用 getModels() 方法获取所有模型,在循环中为所有模型设置场景,然后返回数据提供者.您的示例将更改为以下代码:

Simply get all the models using getModels() method, set scenario for all of them in the loop and then return data provider. Your example will change into following code:

$query = User::find();
$activeData = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
    ],
]);
foreach($activeData->getModels() as $model) {
    $model->scenario = 'statistics';
}
return $activeData;

这篇关于yii2.如何在dataProvider中设置场景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆