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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With