HY。 我有一个ProductController,它扩展了yii \ rest \ ActiveController。 问题是如何通过HTTP GET请求进行查询。
赞:http://api.test.loc/v1/products/search?name=iphone
返回对象将包含名为iphone的所有产品。
答案 0 :(得分:35)
这是我在上一次更新中介绍的方法之一。它始终涉及 gii 生成的搜索类。我喜欢使用它在一个地方定义和维护所有与搜索相关的逻辑,比如使用自定义场景,处理验证或在过滤过程中涉及相关模型(如此example)。所以我回到第一个答案:
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$searchModel = new \app\models\ProductSearch();
return $searchModel->search(\Yii::$app->request->queryParams);
}
然后确保您的搜索类使用load($params,'')
代替load($params)
,或者将其添加到模型类:
class Product extends \yii\db\ActiveRecord
{
public function formName()
{
return '';
}
这应该足以让您的请求看起来像:
这是相同的方法,但通过实施完整的&清洁解决方案:
namespace app\api\modules\v1\controllers;
use yii\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
class ProductController extends ActiveController
{
public $modelClass = 'app\models\Product';
// Some reserved attributes like maybe 'q' for searching all fields at once
// or 'sort' which is already supported by Yii RESTful API
public $reservedParams = ['sort','q'];
public function actions() {
$actions = parent::actions();
// 'prepareDataProvider' is the only function that need to be overridden here
$actions['index']['prepareDataProvider'] = [$this, 'indexDataProvider'];
return $actions;
}
public function indexDataProvider() {
$params = \Yii::$app->request->queryParams;
$model = new $this->modelClass;
// I'm using yii\base\Model::getAttributes() here
// In a real app I'd rather properly assign
// $model->scenario then use $model->safeAttributes() instead
$modelAttr = $model->attributes;
// this will hold filtering attrs pairs ( 'name' => 'value' )
$search = [];
if (!empty($params)) {
foreach ($params as $key => $value) {
// In case if you don't want to allow wired requests
// holding 'objects', 'arrays' or 'resources'
if(!is_scalar($key) or !is_scalar($value)) {
throw new BadRequestHttpException('Bad Request');
}
// if the attr name is not a reserved Keyword like 'q' or 'sort' and
// is matching one of models attributes then we need it to filter results
if (!in_array(strtolower($key), $this->reservedParams)
&& ArrayHelper::keyExists($key, $modelAttr, false)) {
$search[$key] = $value;
}
}
}
// you may implement and return your 'ActiveDataProvider' instance here.
// in my case I prefer using the built in Search Class generated by Gii which is already
// performing validation and using 'like' whenever the attr is expecting a 'string' value.
$searchByAttr['ProductSearch'] = $search;
$searchModel = new \app\models\ProductSearch();
return $searchModel->search($searchByAttr);
}
}
现在您的GET请求将如下所示:
甚至喜欢:
注意:
如果不是/products?name=iphone
,那么您正在寻找特定的
处理搜索或过滤请求的操作,如:
然后,在上面的代码中,您需要删除动作功能及其所有内容:
public function actions() { ... }
重命名:indexDataProvider()
至actionSearch()
&安培;最后添加 'extraPatterns' => ['GET search' => 'search']
到 yii \ web \ UrlManager :: rules ,如上所述
在@KedvesHunor的回答中。
有一种简短的方法可以做到这一点,如果使用 Gii 为您的模型生成CRUD,您定义了一个搜索模型类,那么您可以使用它来过滤结果,您所要做的就是覆盖prepareDataProvider
的{{1}}函数,强制它返回模型的indexAction
函数返回的ActiveDataProvider
实例搜索课程而不是创建自定义的新课程。
如果您的型号 Product.php &您为搜索类生成了 ProductSearch.php ,然后在 Controller 中,您只需添加以下内容:
search
然后要过滤结果,您的网址可能如下所示:
public function actions() {
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider() {
$searchModel = new \app\models\ProductSearch();
return $searchModel->search(\Yii::$app->request->queryParams);
}
甚至是这样:
api.test.loc/v1/products?ProductSearch[name]=iphone
答案 1 :(得分:25)
好的我想通了,只需将它放在你的Controller中并修改配置中的URL路由器。
public function actionSearch()
{
if (!empty($_GET)) {
$model = new $this->modelClass;
foreach ($_GET as $key => $value) {
if (!$model->hasAttribute($key)) {
throw new \yii\web\HttpException(404, 'Invalid attribute:' . $key);
}
}
try {
$provider = new ActiveDataProvider([
'query' => $model->find()->where($_GET),
'pagination' => false
]);
} catch (Exception $ex) {
throw new \yii\web\HttpException(500, 'Internal server error');
}
if ($provider->getCount() <= 0) {
throw new \yii\web\HttpException(404, 'No entries found with this query string');
} else {
return $provider;
}
} else {
throw new \yii\web\HttpException(400, 'There are no query string');
}
}
和URL规则(编辑)
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v1/product'], 'extraPatterns' => ['GET search' => 'search']],
],
],
答案 2 :(得分:8)
我不建议直接使用Superglobals $ _GET。相反,您可以使用Yii::$app->request->get()
。
以下是如何创建通用搜索操作并在控制器中使用它的示例。
在控制器结束
public function actions() {
$actions = [
'search' => [
'class' => 'app\[YOUR NAMESPACE]\SearchAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'params' => \Yii::$app->request->get()
],
];
return array_merge(parent::actions(), $actions);
}
public function verbs() {
$verbs = [
'search' => ['GET']
];
return array_merge(parent::verbs(), $verbs);
}
自定义搜索操作
<?php
namespace app\[YOUR NAMESPACE];
use Yii;
use yii\data\ActiveDataProvider;
use yii\rest\Action;
class SearchAction extends Action {
/**
* @var callable a PHP callable that will be called to prepare a data provider that
* should return a collection of the models. If not set, [[prepareDataProvider()]] will be used instead.
* The signature of the callable should be:
*
* ```php
* function ($action) {
* // $action is the action object currently running
* }
* ```
*
* The callable should return an instance of [[ActiveDataProvider]].
*/
public $prepareDataProvider;
public $params;
/**
* @return ActiveDataProvider
*/
public function run() {
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id);
}
return $this->prepareDataProvider();
}
/**
* Prepares the data provider that should return the requested collection of the models.
* @return ActiveDataProvider
*/
protected function prepareDataProvider() {
if ($this->prepareDataProvider !== null) {
return call_user_func($this->prepareDataProvider, $this);
}
/**
* @var \yii\db\BaseActiveRecord $modelClass
*/
$modelClass = $this->modelClass;
$model = new $this->modelClass([
]);
$safeAttributes = $model->safeAttributes();
$params = array();
foreach($this->params as $key => $value){
if(in_array($key, $safeAttributes)){
$params[$key] = $value;
}
}
$query = $modelClass::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (empty($params)) {
return $dataProvider;
}
foreach ($params as $param => $value) {
$query->andFilterWhere([
$param => $value,
]);
}
return $dataProvider;
}
}
答案 3 :(得分:2)
在Config / web.php中 - &gt;添加'extraPatterns'=&gt; ['GET search'=&gt; '搜索'] 强>
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [['class' => 'yii\rest\UrlRule', 'controller' => 'v1/basicinfo', 'pluralize'=>false,'extraPatterns' => ['GET search' => 'search']]]]
**静止Api控制器: - Moduels / v1 / controllers / **
basicinfo: - 您的控制器名称,姓名和年龄是您的字段名称。您可以添加表格中存在的所有参数。
搜索网址LIKE: - basicinfo / search?name = yogi&amp; age = 12-23
包括使用yii \ data \ ActiveDataProvider;
public function actionSearch()
{
if (!empty($_GET)) {
$model = new $this->modelClass;
foreach ($_GET as $key => $value) {
if (!$model->hasAttribute($key)) {
throw new \yii\web\HttpException(404, 'Invalid attribute:' . $key);
}
}
try {
$query = $model->find();
foreach ($_GET as $key => $value) {
if ($key != 'age') {
$query->andWhere(['like', $key, $value]);
}
if ($key == 'age') {
$agevalue = explode('-',$value);
$query->andWhere(['between', $key,$agevalue[0],$agevalue[1]]);
}
}
$provider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'updated_by'=> SORT_DESC
]
],
'pagination' => [
'defaultPageSize' => 20,
],
]);
} catch (Exception $ex) {
throw new \yii\web\HttpException(500, 'Internal server error');
}
if ($provider->getCount() <= 0) {
throw new \yii\web\HttpException(404, 'No entries found with this query string');
} else {
return $provider;
}
} else {
throw new \yii\web\HttpException(400, 'There are no query string');
}
}
答案 4 :(得分:0)
从yii 2.0.13开始,yii\rest\IndexAction
具有新属性-dataFilter
,从而简化了过滤过程。默认情况下,ActiveController将yii\rest\IndexAction
用于index
操作:
class ActiveController extends Controller {
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
]
}
}
在ProductController
控制器中执行以下操作:
class ProductController extends ActiveController
{
public function actions()
{
$actions = parent::actions();
$actions['index']['dataFilter'] = [
'class' => 'yii\data\ActiveDataFilter',
'searchModel' => 'app\models\ProductSearch'
];
return $actions;
}
}
假设app\models\ProductSearch
是产品过滤器模型。
答案 5 :(得分:0)
如果您需要访问自己的api,例如:api/product/index?name=fashion
较短的过滤方法是:
-取消操作,在我的情况下为index
操作。
public function actions()
{
$actions = parent::actions();
unset($actions['index']);
return $actions;
}
执行一个自定义查询,如下所示。
公共功能actionIndex(){
$query = Product::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 1,
],
]);
if (isset($_GET['name']) && !empty($_GET['name'])) {
$searchWord = strtolower(trim($_GET['name']));
$query->andFilterWhere(['like', 'name', $searchWord]);
}
return $dataProvider;
}
答案 6 :(得分:0)
如果你想按唯一字段搜索,这里有一个较短的版本,只获取一条记录:
public function actionSearch()
{
if (!empty($_GET)) {
$model = new $this->modelClass;
return $model::findOne($_GET);
} else {
throw new HttpException(400, 'There are no query string');
}
}
用法:http://example.com/api/search?slug=abs