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

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

WBOY
WBOYOriginal
2016-06-06 20:27:421431Durchsuche

就是用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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn