Yii2. How to set scenario in dataProvider?

2019-06-21 05:05发布

问题:

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;


标签: yii2