【发布时间】:2017-03-15 14:43:59
【问题描述】:
我正在尝试利用 YII2 REST API(基于高级模板)来创建我自己的服务。我目前正在成功使用以下 URL 向我返回一条“文章”记录:
http://service/articles/view?id=1
我现在正在尝试复制此代码,以便它适用于另一种记录类型。我的新记录有一个名为“key”的主键,我想用它来搜索。因此,我需要将参数名称“id”更改为“key”。
有人能解释一下如何在此 URL 上指定除“id”之外的参数吗?每当我省略 id 作为参数时,我都会收到“错误请求:缺少必需参数:id”。我不明白这个必需参数来自哪里以及如何更改或添加它。
相关类如下所示:
class ArticleController extends ActiveController
{
/**
* @var string
*/
public $modelClass = 'frontend\modules\api\v1\resources\Article';
/**
* @var array
*/
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items'
];
/**
* @inheritdoc
*/
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'prepareDataProvider' => [$this, 'prepareDataProvider']
],
'view' => [
'class' => 'yii\rest\ViewAction',
'modelClass' => $this->modelClass,
'findModel' => [$this, 'findModel']
],
'options' => [
'class' => 'yii\rest\OptionsAction'
]
];
}
/**
* @return ActiveDataProvider
*/
public function prepareDataProvider()
{
return new ActiveDataProvider(array(
'query' => Article::find()->published()
));
}
/**
* @param $id
* @return array|null|\yii\db\ActiveRecord
* @throws HttpException
*/
public function findModel($id)
{
$model = Article::find()
->published()
->andWhere(['id' => (int) $id])
->one();
if (!$model) {
throw new HttpException(404);
}
return $model;
}
}
class Article extends \common\models\Article implements Linkable
{
public function fields()
{
return ['id', 'slug', 'category_id', 'title', 'body', 'published_at'];
}
public function extraFields()
{
return ['category'];
}
/**
* Returns a list of links.
*
* @return array the links
*/
public function getLinks()
{
return [
Link::REL_SELF => Url::to(['article/view', 'id' => $this->id], true)
];
}
}
提前致谢。
编辑:“前端”文件夹结构中 urlManager 的规范如下:
<?php
return [
'class'=>'yii\web\UrlManager',
'enablePrettyUrl'=>true,
'showScriptName'=>false,
'rules'=> [
// Pages
['pattern'=>'page/<slug>', 'route'=>'page/view'],
// Articles
['pattern'=>'article/index', 'route'=>'article/index'],
['pattern'=>'article/attachment-download', 'route'=>'article/attachment-download'],
['pattern'=>'article/<slug>', 'route'=>'article/view'],
// Api
['class' => 'yii\rest\UrlRule', 'controller' => 'api/v1/article', 'only' => ['index', 'view', 'options']],
['class' => 'yii\rest\UrlRule', 'controller' => 'api/v1/user', 'only' => ['index', 'view', 'options']]
]
];
【问题讨论】:
-
查看ViewAction文档:yiiframework.com/doc-2.0/yii-rest-viewaction.html#run()-detail,默认需要接收
$id参数。我要做的是创建一个新操作,比如说view2,然后添加您需要的功能。 -
看起来您使用的规则与 default yii2 routing for REST 通常实施的规则不同。您能否也显示您的
urlManager设置? -
感谢您的回复,@gmc。如果我按照您的建议创建一个新方法,您是否知道(或者可以让我参考文档)在哪里配置“id”值?
-
@Salem,我不确定在哪里可以找到 urlManager 设置(我有点新手)。
-
您会在配置文件中找到它。这是定义您的 url
rules的地方。你会在我之前评论中链接的文档中看到它。