Yii2 REST 查询 [英] Yii2 REST query

查看:32
本文介绍了Yii2 REST 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.我有一个扩展 yii\rest\ActiveController 的 ProductController.问题是我如何通过 HTTP GET 请求进行查询.

Hy. I have a ProductController which extends the yii\rest\ActiveController. Question is that how can i make querys via HTTP GET request.

喜欢:http://api.test.loc/v1/products/search?name=iphone

返回对象将包含名称为 iphone 的所有产品.

And the return object will contains all products with name iphone.

推荐答案

好的,我想通了,只需将其放在您的控制器中并在配置中修改 URL 路由器.

Ok i figured out, just put this in your Controller and modifiy the URL router in config.

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 规则(编辑)

And the URL rule (edit)

'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/product'], 'extraPatterns' => ['GET search' => 'search']],
        ],
    ],

这篇关于Yii2 REST 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆