现在我的视图网址看起来像example.com/item/view?id=1
,我需要它看起来像这样:example.com/item/item-name
。据我所知,我需要使用SluggableBehavior。但是如何配置我的URLManager规则和SluggableBehavior来访问它?
答案 0 :(得分:1)
您需要在UrlManager
中配置规则:
[
'components' => [
'urlManager' => [
// ...
'rules' => [
'item/<slug:[\w\-]+>' => 'item/view',
// ...
],
],
],
]
然后你创建这样的URL:
Url::to(['item/view', 'slug' => $model->slug]);
行动中:
public function actionView($slug) {
$model = Item::findOne(['slug' => $slug]);
// rest of action logic
}
值得一看 handling pretty URLs documentation。
配置SluggableBehavior
为quite well documented:
public function behaviors()
{
return [
[
'class' => SluggableBehavior::className(),
'attribute' => 'title',
// 'slugAttribute' => 'slug',
],
];
}