我有一张桌子
--------------------
id |title | slug
--------------------
1 | name_1 |
--------------------
1 | name_2 |
--------------------
如何使用yii2 sluggable behavior
从colunm“title”更新列slug下面的代码不起作用
$this->update('event', ['slug' => (new Expression(Inflector::slug('title')))]);
答案 0 :(得分:0)
将SluggableBehavior添加到模型
use yii\behaviors\SluggableBehavior;
class YourModel extends \yii\db\ActiveRecord
{
public function behaviors()
{
return [
[
'class' => SluggableBehavior::className(),
'attribute' => 'title',
// 'slugAttribute' => 'slug',
],
];
}
由于我们的列名为slug,因此框架默认为slugAttribute是不需要的。
答案 1 :(得分:0)
我使用写控制台操作的最佳解决方案,如
public function actionEventSlugs(){
$events = \frontend\models\Events::find()->all();
foreach($events as $event){
$slug = \yii\helpers\Inflector::slug($event->title);
$event->slug = $slug;
// $this->stdout($slug."/n");
$event->update(false);
}
}
然后启动控制台并执行命令
yii build/event-slug
这对您的制作也会更好。 这里'build'是控制器名称
愿它有所帮助
由于