php 带有复合主键的 Yii 模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8985304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yii Model with composite primary key
提问by Nathan H
My MySQL table's primary is a composite of 2 columns: space_id (INTEGER) and day (DATE).
我的 MySQL 表的主表是 2 列的组合:space_id (INTEGER) 和 day (DATE)。
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;
It works fine in raw SQL, it complains if I try to create a duplicate, but lets me create rows the the same day or the same space_id.
它在原始 SQL 中运行良好,如果我尝试创建重复项,它会抱怨,但让我在同一天或相同的 space_id 创建行。
However, in Yii when using new Object() and save(), it complains as if "space_id" has to be unique.
然而,在 Yii 中使用 new Object() 和 save() 时,它会抱怨好像“space_id”必须是唯一的。
I used "Giix" to generate the model if it matters.
如果重要的话,我使用“Giix”来生成模型。
I tried to add this code to the model, but it didn't help:
我尝试将此代码添加到模型中,但没有帮助:
public function primaryKey(){
return array('space_id', 'day');
}
回答by cebe
Adding this code to your ActiveRecord class is okay, but should not be necessary because Yii already has that information from your MySQL table declaration.
将此代码添加到您的 ActiveRecord 类是可以的,但不是必需的,因为 Yii 已经从您的 MySQL 表声明中获得了该信息。
public function primaryKey(){
return array('space_id', 'day');
}
When Yii complains about "space_id" to be unique, giix might have added a validation rule to rules() in your ActiveRecord class. These rules are checked before an ActiveRecord is saved and it will only save if all rules are okay. Read the Data Validation section of Definitive Guidefor more information.
当 Yii 抱怨“space_id”是唯一的时,giix 可能在您的 ActiveRecord 类中的 rules() 中添加了验证规则。在保存 ActiveRecord 之前检查这些规则,并且只有在所有规则都正常时才会保存。阅读权威指南的数据验证部分了解更多信息。
回答by Orphaned Record
From what I understand since Yii 1.1 composite primary keys are not longer supported with Gii, which is frustrating many developers. There are other poorly documented alterations needed in your code aside from the returning an array as a primary key.
据我了解,由于 Gii 不再支持 Yii 1.1 复合主键,这让许多开发人员感到沮丧。除了将数组作为主键返回之外,您的代码中还需要其他一些记录不佳的更改。
The best explanation I found was in this discussion in the Yii forum.