Yii2在URL中显示模型名称

时间:2018-04-13 12:01:56

标签: url yii2

现在我的视图网址看起来像example.com/item/view?id=1,我需要它看起来像这样:example.com/item/item-name。据我所知,我需要使用SluggableBehavior。但是如何配置我的URLManager规则和SluggableBehavior来访问它?

1 个答案:

答案 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

配置SluggableBehaviorquite well documented

public function behaviors()
{
    return [
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
            // 'slugAttribute' => 'slug',
        ],
    ];
}