Yii2 REST查询 [英] Yii2 REST query

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

问题描述

海兰。
我有它扩展了警予\\其他\\ ActiveController一个ProductController的。
问题是,如何通过HTTP GET请求做出querys。

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

我爱:<一href=\"http://api.test.loc/v1/products/search?name=iphone\">http://api.test.loc/v1/products/search?name=iphone

和返回的对象将包含一个名为iPhone的所有产品。

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

推荐答案

好吧,我想通了,只是把这个在你的控制器,并在配置modifiy的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天全站免登陆