O
O
Orbb2018-07-02 18:39:27
Yii
Orbb, 2018-07-02 18:39:27

Is it possible to get records of a specific user without overriding ActiveController methods?

I inherit from ActiveController. Now, when I get access to index, I get ALL records. How to limit the receipt of records to the very user that requests? I mean, is it possible to enter restrictions somewhere without redefining the default behavior? checkAccess some, for example. Or is it impossible and necessary to override the default methods and use the search model?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kim, 2018-07-03
@kimono

If it's only about actionIndex, then you will have to at least inherit from ActiveController and use your own IndexAction:

class MyActiveController extends yii\rest\ActiveController {
  public function actions(){
    return ArrayHelper::merge(parent::actions(), [
      'index' => [
        'class' => 'common\components\IndexAction'
      ]
    ]);
  }
}

class IndexAction extends yii\rest\IndexAction {
    /**
     * Prepares the data provider that should return the requested collection of the models.
     * @return ActiveDataProvider
     */
    protected function prepareDataProvider()
    {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }

        $filter = null;
        if ($this->dataFilter !== null) {
            $this->dataFilter = Yii::createObject($this->dataFilter);
            if ($this->dataFilter->load($requestParams)) {
                $filter = $this->dataFilter->build();
                if ($filter === false) {
                    return $this->dataFilter;
                }
            }
        }

        if ($this->prepareDataProvider !== null) {
            return call_user_func($this->prepareDataProvider, $this, $filter);
        }

        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        // чтобы переделать это
        //$query = $modelClass::find();
        $query = $modelClass::find()->where(['user_id' => Yii::$app->user->id]);
        if (!empty($filter)) {
            $query->andWhere($filter);
        }

        return Yii::createObject([
            'class' => ActiveDataProvider::className(),
            'query' => $query,
            'pagination' => [
                'params' => $requestParams,
            ],
            'sort' => [
                'params' => $requestParams,
            ],
        ]);
    }
}

PS: and this is provided that all models that are accessed through this controller have user_id.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question