Yii INSERT ...在重复更新时 [英] Yii INSERT ... ON DUPLICATE UPDATE

查看:171
本文介绍了Yii INSERT ...在重复更新时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个Yii项目.如何使用MySQL的ON DUPLICATE功能( http:在Yii模型上执行save()时//dev.mysql.com/doc/refman/5.0/zh-CN/insert-on-duplicate.html )?

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,天)中有重复项,我不想让它抱怨,我只希望它使用最新数据进行更新.

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 ...在重复更新时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆