php – Yii INSERT …重复更新

栏目: PHP · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/9004269/yii-insert-on-duplicate-update
我正在研究Yii项目.在Yii模型上执行save()时,如何使用MySQL( http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

)的ON DUPLICATE功能?

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

我知道如何在原始 SQL 中执行此操作,我只是想知道是否有一个干净的Yii方法来做到这一点.

你正在使用Yii中的模型,它非常简单..尝试加载你怀疑有重复条目的模型,如果你发现模型被加载的条目,则返回null.现在,如果您的模型为null,则只需创建新模型. rest是插入新记录的正常代码.

//try to load model with available id i.e. unique key
$model = someModel::model()->findByPk($id);  

//now check if the model is null
if(!$model) $model = new someModel();

//Apply you new changes
$model->attributes = $attributes;

//save
$model->save();

请参阅示例应用程序Yii博客中的post controllers update方法.对于函数名称的拼写我可能有问题,对不起.

翻译自:https://stackoverflow.com/questions/9004269/yii-insert-on-duplicate-update


以上所述就是小编给大家介绍的《php – Yii INSERT …重复更新》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms in C++

Algorithms in C++

Robert Sedgewick / Addison-Wesley Professional / 1992-05-10 / USD 64.99

This version of Sedgewick's bestselling book provides a comprehensive collection of algorithms implemented in C++. The algorithms included cover a broad range of fundamental and more advanced methods:......一起来看看 《Algorithms in C++》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具