Answers
在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 9 years, 2 months ago