gpt4 book ai didi

cakephp - 在 CakePHP 中保存记录时使用 'on duplicate key update'

转载 作者:行者123 更新时间:2023-12-04 19:12:55 25 4
gpt4 key购买 nike

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

更新所述记录时我只有字母数字 ID,所以我需要向保存函数添加一个“重复 key 更新”语句,但我该怎么做?

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

最佳答案

另一种选择是覆盖 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);
}

关于cakephp - 在 CakePHP 中保存记录时使用 'on duplicate key update',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13396272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com