您的操作应该接受一个参数$id
:
public function actionView($id) {
$model = $this->loadModel($id);
您需要做的是在同一个控制器中修改 loadModel 函数:
/**
* @param integer or string the ID or slug of the model to be loaded
*/
public function loadModel($id) {
if(is_numeric($id)) {
$model = Page::model()->findByPk($id);
} else {
$model = Page::model()->find('slug=:slug', array(':slug' => $id));
}
if($model === null)
throw new CHttpException(404, 'The requested page does not exist.');
if($model->hasAttribute('isDeleted') && $model->isDeleted)
throw new CHttpException(404, 'The requested page has been deleted for reasons of moderation.');
// Not published, do not display
if($model->hasAttribute('isPublished') && !$model->isPublished)
throw new CHttpException(404, 'The requested page is not published.');
return $model;
}
然后,您需要修改 urlManager 规则以接受一个字符串,而不仅仅是一个 ID:
:\d+
在下面的默认规则中删除:
'<controller:\w+>/<id:\d+>' => '<controller>/view',
它应该是这样的:
'<controller:\w+>/<id>' => '<controller>/view',
还有一点需要注意,如果您要走这条路,请确保 slug 在您的数据库中是唯一的,并且您还应该在模型中强制执行验证规则:
array('slug', 'unique'),