Answer the question
In order to leave comments, you need to log in
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
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,
],
]);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question