【发布时间】:2016-08-18 06:31:51
【问题描述】:
我正在使用 Yii2 创建博客我希望帖子 URL 是帖子的年、月和段。我有 slug 目前正在努力验证自己,但我不确定如何告诉 sluggable 行为在生成唯一 slug 时考虑年份和月份。
在我的帖子表中,我有一个 slug(基于帖子标题)和 published_at 日期时间。我目前有以下设置,它根据年、月和 slug 检索给定的帖子。
urlManager 有'/<year:\d{4}>/<month:\d{2}>/<slug>' => 'post/view',,在我的控制器中如下:
public function actionView($year, $month, $slug)
{
$model = $this->findModel($year, $month, $slug);
return $this->render('view', [
'model' => $model,
]);
}
...
protected function findModel($year, $month, $slug)
{
$model = Post::find()
->where(['slug' => $slug])
->andWhere(['FROM_UNIXTIME(publish_at, "%m")' => $month])
->andWhere(['FROM_UNIXTIME(publish_at, "%Y")' => $year])
->one();
if ($model !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested post does not exist.');
}
}
目前,Post 模型只定义了以下行为。
'SluggableBehavior' => [
'class' => SluggableBehavior::className(),
'attribute' => 'title',
'immutable' => true,
'ensureUnique' => true,
],
如何编辑行为,以便在确定唯一性时评估年、月和段?
我是否可能需要将年份和月份存储在数据库中,而不是动态地将它们从 published_at 日期时间中提取出来(我目前在 find() 期间这样做)?
【问题讨论】:
标签: yii2