Mr.White
Mr.White

Reputation: 25

Yii2 Sluggable Behavior update existing rows in DB

I have a table

--------------------
 id |title   | slug
--------------------
 1  | name_1 | 
--------------------
 1  | name_2 | 
--------------------

How can i update column slug from colunm "title" using yii2 sluggable behavior

Code bellow don't work

$this->update('event', ['slug' => (new Expression(Inflector::slug('title')))]);

Upvotes: 1

Views: 866

Answers (2)

Ansari Khalid
Ansari Khalid

Reputation: 57

Best solution I used write console action like

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);
    }
}

and start the console and simply execute the command

yii build/event-slug

This could better for your production also. Here 'build' is the controller name

May it helps

Thanks

Upvotes: 0

Muhammad Shahzad
Muhammad Shahzad

Reputation: 9652

Add the SluggableBehavior to the Model

use yii\behaviors\SluggableBehavior;

class YourModel extends \yii\db\ActiveRecord
{

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

The slugAttribute isn't needed since our column is called slug, the framework default.

Upvotes: 0

Related Questions