Yii INSERT ...在重复更新时

编程入门 行业动态 更新时间:2024-10-27 22:20:02
本文介绍了Yii INSERT ...在重复更新时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在做一个Yii项目.如何使用MySQL的ON DUPLICATE功能( http:在Yii模型上执行save()时//dev.mysql/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 ( dev.mysql/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 ...在重复更新时

本文发布于:2023-10-23 03:33:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Yii   INSERT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!