Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign uuid to a model in yii2

Tags:

php

mysql

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?

like image 235
Mischa Avatar asked Sep 12 '25 07:09

Mischa


1 Answers

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

like image 127
Florian Gee Avatar answered Sep 14 '25 21:09

Florian Gee