Yii2 REST API按字段查找

时间:2016-06-01 09:23:39

标签: yii2 yii-rest

这是api url。

  

/ API /网络/ V1 /用户/ 123

按ID查找用户。如何更改规则以token查找,而不是id

这是一条规则:

            [
                'class' => 'yii\rest\UrlRule',
                'controller' => ['v1/users'],
                'tokens' => [
                    '{id}' => '<id:\\w+>'

                   // this does not work  
                   // '{token}' => '<token:\\w+>'
                ],
            ],

1 个答案:

答案 0 :(得分:1)

定义为令牌的{id}是内置yii\rest\ViewAction使用的那个代码是这样的:

class ViewAction extends Action
{
    /**
     * Displays a model.
     * @param string $id the primary key of the model.
     * @return \yii\db\ActiveRecordInterface the model being displayed
     */
    public function run($id)
    {
        $model = $this->findModel($id);
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id, $model);
        }

        return $model;
    }
}

$this->findModel($id)yii\rest\Action下定义,它使用主键找到模型。如果您需要使用其他令牌(如{token})并在与其主键不同的属性中找到您的模型,则需要覆盖控制器内的视图操作。

以下是在您的规则中添加'{token}' => '<token:\\w+>'时应该有效的示例:

class UserController extends ActiveController
{
    ...
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['view']);
        return $actions;
    }

    public function actionView($token){
        $modelClass = $this->modelClass;
        $model = $modelClass::find()->where(['token' => $token])->one();

        if ($model === null)
            throw new \yii\web\NotFoundHttpException("Uknown user having $token as token");

        return $model;
    }

}

另请注意,您需要更改$patterns以支持新生成的user-select: none;。您的最终规则可能如下所示:

'rules' => [
    [
        'class' => 'yii\rest\UrlRule', 
        'controller' => ['v1/users'],  
        'tokens' => [
            '{id}' => '<id:\\w+>',
            '{token}' => '<token:\\w+>'
        ]
        'patterns' => [
            'PUT,PATCH {id}' => 'update',
            'DELETE {id}' => 'delete',
            // {token} is assigned to $token when redirecting to view
            'GET,HEAD {token}' => 'view',
            'POST' => 'create',
            'GET,HEAD' => 'index',
            '{id}' => 'options',
            '' => 'options',
        ],
    ],
]