How do I use YII2 ActiveRecord to implement the default primary key as a UUID when working with all MySQL table inserts?

Source: Internet
Author: User
Tags uuid
This is the one with MySQL.




select uuid();


What to do with the ActiveRecord.


id = 'uuid()';...$model->save();


Problem: Obviously the above method is not possible, there is no other way to deal with






Reply content:



This is the one with MySQL.


select uuid();


What to do with the ActiveRecord.


id = 'uuid()';...$model->save();


Problem: Obviously the above method is not possible, there is no other way to deal with






It is possible to add a primarykeybehavior to the activerecord::behaviors () to deal with Activerecord::event_before_insert.


class PrimaryKeyBehavior extends AttributeBehavior
{
    public $primaryKeyAttribute = 'id';
    
    public $value;

    public function init()
    {
        parent::init();

        if (empty($this->attributes)) {
            $this->attributes = [
                BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->primaryKeyAttribute],
            ];
        }
    }

    protected function getValue($event)
    {
        return new Expression('UUID()');
    }

}


Called in the model.


class Test extends \yii\db\ActiveRecord
{
    ...
    public function behaviors()
    {
        return [
            \common\behaviors\PrimaryKeyBehavior::className(),
        ];
    }
    ...
}


This approach allows for flexible invocation, called in the required model, and does not include $model->id = uuid when writing logic






Determine if the ID is a string type, and then try this:


$model->id = new \yii\db\Expression('uuid()')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.