Yii2. How to set scenario in dataProvider?

半城伤御伤魂 提交于 2019-12-10 15:19:50

问题


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

Fields in User model:

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

回答1:


What about using the $select property?

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

Or even better, create an ActiveQuery class for them:

class UserQuery extends ActiveQuery
{
     public function statistics()
     {
        return $this->select(['id','email','count']);
     }

     /* add as many filtering functions as you need here */
}

Then override the find() method in the User class to use it:

public static function find()
{
    return new \app\models\UserQuery(get_called_class());
}

Then do:

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

Note: In default implementation of Yii2 RESTful API you can also select the required fields within url by doing: GET /users?fields=id,email,count




回答2:


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;


来源:https://stackoverflow.com/questions/43840406/yii2-how-to-set-scenario-in-dataprovider

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!