Answer the question
In order to leave comments, you need to log in
How to filter a selection of values from a table in REST Yii using other fields (not just id)?
There is a url like: back.ru/rest/10
I will get a user with id 10 using it.
But how can I get a user with a name equal to Petya, for example?
Well, that is, what would the link look like this: back.ru/rest/?name=some_name
or something like that. Is this possible at all in rest yii?
My controller:
<?php
namespace backend\controllers;
use yii\rest\ActiveController;
use backend\models\Test;
class RestController extends ActiveController
{
public $modelClass = Test::class;
public function checkAccess($action, $model = null, $params = [])
{
return true;
}
public function behaviors() {
return [
'contentNegotiator' => [
'class' => \yii\filters\ContentNegotiator::class,
'formatParam' => '_format',
'formats' => [
'application/json' => \yii\web\Response::FORMAT_JSON,
'xml' => \yii\web\Response::FORMAT_XML
],
],
];
}
}
<?php
namespace backend\models;
class Test extends \yii\db\ActiveRecord
{
public function rules()
{
return [
[['name', 'age'], 'required'],
['name', 'string'],
['age', 'integer'],
];
}
}
Answer the question
In order to leave comments, you need to log in
You inherit from ActiveController which creates methods out of the box in a methodactions
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'view' => [
'class' => 'yii\rest\ViewAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'create' => [
'class' => 'yii\rest\CreateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->createScenario,
],
'update' => [
'class' => 'yii\rest\UpdateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->updateScenario,
],
'delete' => [
'class' => 'yii\rest\DeleteAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'options' => [
'class' => 'yii\rest\OptionsAction',
],
];
}
'dataFilter' => [
'class' => 'yii\data\ActiveDataFilter',
'searchModel' => 'path/To/Search,
],
$searchModel = new \app\models\SearchModel();
return $searchModel->search(\Yii::$app->request->queryParams);
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$searchModel = new \app\models\SearchModel();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
return $dataProvider;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question