纯蛋糕选择
有很多方法可以做到这一点......
我认为最少的代码侵入性是在相应模型的beforeSave 中添加一个检查,类似于
public function beforeSave() {
if (!$this->id && !isset($this->data[$this->alias][$this->primaryKey])) {
// insert
$this->data[$this->alias]['uuid'] = $this->createUUID();
} else {
// edit
// if you don't want to do anything on insert, delete this "else"
}
return true;
}
(该代码是从 here 复制的)。
现在,您没有提供太多关于 uuid 应该是什么的详细信息(整数、长度、可读单词...)。但是让我们假设它是一个简单的整数,如果不是,所有的更改都需要在这里完成。在同一个模型中,添加一个函数来创建uuid
private function createUUID() {
do {
$uuid = rand(); //any logic you want to create the uuid, a md5, substring, hash...
//check for no repetition
$help = $this->find('first', array('conditions'=>array('uuid'=>$uuid)));
} while(!empty($help));
return $uuid;
}
这样,您将拥有一个唯一的 uuid,仅在插入时添加,无需更改其余代码。
这是我喜欢的解决方案。
现在,另一种方法是创建返回值的 UUID 函数,并在 afterSave 中使用它(检查它是插入还是更新)并更新使用 uuid 记录(届时您将拥有新创建记录的 ID)。
两者相比没有太大优势...beforeSaveone 允许您将数据库中的 uuid 字段设置为 NOT NULL,而如果您使用 afterSave,则需要先插入记录,并且 uuid 应该为 null。
没有太多细节,我推荐beforeSave 选项,只是因为我的uuid NOT NULL 东西。