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

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

WBOY
WBOYOriginal
2016-06-06 20:27:421430browse

就是用Mysql自带的这个

<code>select uuid();</code>

在ActiveRecord里该如何处理

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

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

回复内容:

就是用Mysql自带的这个

<code>select uuid();</code>

在ActiveRecord里该如何处理

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

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

在ActiveRecord::behaviors()里增加一个PrimaryKeyBehavior来处理ActiveRecord::EVENT_BEFORE_INSERT这种方法可行

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

}</code>

在model里调用

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

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

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

<code>$model->id = new \yii\db\Expression('uuid()');
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn