How can I use yii2ActiveRecord to implement the simple method of setting the default primary key as uuid when processing insert operations on all mysql tables?

Source: Internet
Author: User
This {code...} comes with Mysql ...} how to deal with {code...} In ActiveRecord ...} problem: Obviously, this method is not feasible. Is there any other way to handle this problem that comes with Mysql?

select uuid();

What should I do in ActiveRecord?


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

Problem: Obviously, this method is not feasible. Is there any other processing method?

Reply content:

This is the built-in Mysql

select uuid();

What should I do in ActiveRecord?


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

Problem: Obviously, this method is not feasible. Is there any other processing method?

Add a PrimaryKeyBehavior in ActiveRecord: behaviors () to process ActiveRecord: EVENT_BEFORE_INSERT. This method is feasible.

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

Call in model

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

This method can be flexibly called, and called in a Model that is needed, without adding $ model-> id = uuid () when writing logic ()

Make sure that the id is of the string type and try again as follows:

$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.