6

我的模型有 2 个唯一索引。主键和字母数字 ID。

更新所述记录时我只有字母数字 id,所以我需要在保存功能中添加“重复键更新”语句,但我该怎么做呢?

而且我不想先查询主键,因为这会使导入过程变得异常漫长和缓慢。

4

2 回答 2

3

另一种选择是Model->exists()在您的模型中覆盖。这实际上和 Cake 做的一样,但扩展到了其他键,不仅是 primaryKey。

/**
 * Overrides Model->exists() method so we can check for uniqueness if primary key is not set
 *
 * If a record already exists, sets the primary key of that record to do an update
 *
 * @param int $id
 * @return bool True if the record exists, false otherwise
 */
public function exists($id = null)
{
    if (empty($id) && !$this->getID() && isset($this->data[$this->alias]) && is_array($this->data[$this->alias])) {
        // given $id and primary key are empty, try with data
        $exists = $this->find('first', array(
            'fields' => array($this->primaryKey),
            'conditions' => array(
                'key1'=>$this->data[$this->alias]['key1'],
                'key2'=>$this->data[$this->alias]['key2'],
            ),
            'recursive' => -1,
            'callbacks' => false,
        ));
        if ($exists) {
            $this->set($this->primaryKey, $exists[$this->alias][$this->primaryKey]);
            return true;
        }
    }
    return parent::exists($id);
}
于 2014-07-24T08:31:16.930 回答
2

cakephp 中不支持“重复密钥更新”选项。

如果您真的不想进行查找,我建议将字母数字 id 更改为主键(只要它类似于 UUID 而不是 varchar)。如果这不是一个选项,我最好的建议是添加一个执行完整性检查的 beforeSave 方法。

这是一个可以帮助Cakephp 检查记录是否存在的链接

于 2013-01-16T20:29:17.513 回答