Yii INSERT ... ON DUPLICATE UPDATE(Yii INSERT ... 重复更新)
问题描述
我正在做一个 Yii 项目.如何使用 MySQL 的 ON DUPLICATE 功能(http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html ) 在 Yii 模型上执行 save() 时?
I am working on a Yii project. How can I use the ON DUPLICATE feature of MySQL ( http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html ) when doing a save() on a Yii model?
我的MySQL如下:
CREATE TABLE `ck_space_calendar_cache` (
`space_id` int(11) NOT NULL,
`day` date NOT NULL,
`available` tinyint(1) unsigned NOT NULL DEFAULT '0',
`price` decimal(12,2) DEFAULT NULL,
`offer` varchar(45) DEFAULT NULL,
`presale_date` date DEFAULT NULL,
`presale_price` decimal(12,2) DEFAULT NULL,
`value_x` int(11) DEFAULT NULL,
`value_y` int(11) DEFAULT NULL,
PRIMARY KEY (`space_id`,`day`),
KEY `space` (`space_id`),
CONSTRAINT `space` FOREIGN KEY (`space_id`) REFERENCES `ck_space` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我的PHP如下:
$cache = new SpaceCalendarCache();
$cache->attributes = $day; //Some array with attributes
$cache->save();
如果我的主键 (sapce_id,day) 中存在重复项,我不希望它抱怨,我只希望它使用最新数据进行更新.
If there is a duplicate in my primary key (sapce_id,day), I don't want it to complain, I just want it to update with the latest data.
我知道如何在原始 SQL 中做到这一点,我只是想知道是否有一种干净的 Yii 方法来做到这一点.
I know how to do it in raw SQL, I was just wondering if there is a clean Yii way to do it.
推荐答案
我在 beforeValidate() 中检查了是否存在重复项.如果有,我设置 $this->setIsNewRecord(false);
I overrode beforeValidate() where I checked if a duplicate exists. If one does, I set $this->setIsNewRecord(false);
似乎有效.不确定它的性能如何.
Seems to work. Not sure how performant it is.
这篇关于Yii INSERT ... 重复更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Yii INSERT ... 重复更新


基础教程推荐
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01