就是用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>
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号