Mischa
Mischa

Reputation: 1601

Assign uuid to a model in yii2

Is there any way to assign a database function-call to a model attribute in Yii2?

Something like:

$myModel->myAttribute = 'mysql:UUID()';
$myModel->save();

Or how would i do this, if i want to fill the attribute with the uuid on save?

Upvotes: 4

Views: 4058

Answers (2)

Faisal
Faisal

Reputation: 11

To generate the UUID during CREATE action add the following function to your MODEL if get any error to save

public function beforeSave($insert)
{
    if ($this->isNewRecord)
        $this->myAttribute = new yii\db\Expression('UUID()');
    return parent::beforeSave($insert);
}

Upvotes: 1

Florian Gee
Florian Gee

Reputation: 113

What you could do is using the yii\db\Expression class:

$myModel->myAttribute = new yii\db\Expression('UUID()');
$myModel->save();

https://www.yiiframework.com/doc/api/2.0/yii-db-expression

And if you want to set the UUID on create insert the following function in your model class:

public function beforeSave($insert)
{
        if($insert === self::EVENT_BEFORE_INSERT){
                $this->myAttribute = new yii\db\Expression('UUID()');
        }
        return parent::beforeSave($insert);
}

https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#beforeSave()-detail

Upvotes: 5

Related Questions