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

WBOY
Release: 2016-06-06 20:27:42
Original
1430 people have browsed it

就是用Mysql自带的这个

<code>select uuid();</code>
Copy after login
Copy after login

在ActiveRecord里该如何处理

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

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

回复内容:

就是用Mysql自带的这个

<code>select uuid();</code>
Copy after login
Copy after login

在ActiveRecord里该如何处理

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

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

在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>
Copy after login

在model里调用

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

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

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

<code>$model->id = new \yii\db\Expression('uuid()');
</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!