我正在做一个 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。现在,如果您的模型为空,只需创建新模型。 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 博客中的后 Controller 更新方法。我可能对函数名称的拼写有误,对此深表歉意。
关于php - Yii INSERT ... 重复更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9004269/