如何用yii2 ActiveRecord在处理mysql所有表insert的时候,实现默认主键为uuid的简便方法吗?


就是用Mysql自带的这个


 select uuid();

在ActiveRecord里该如何处理


 <?php
$model = new xx();
$model->id = 'uuid()';
...
$model->save();

问题:显然上面这种方法是不行的,有没有其他的处理方式

yii2 php mysql

Alyssa 8 years, 7 months ago

确定 id 是字符串类型, 然后试下这样:


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

曾经是小正太 answered 8 years, 7 months ago

在ActiveRecord::behaviors()里增加一个PrimaryKeyBehavior来处理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()');
    }

}

在model里调用


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

这种方法可以实现灵活调用,在有需要的Model里调用,并且不用在写逻辑的时候加上$model->id = uuid()

风灵与炎蝶之环 answered 8 years, 7 months ago

Your Answer