简体   繁体   English

具有复合主键的Yii模型

[英]Yii Model with composite primary key

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中使用新的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');
        }

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. 当Yii抱怨“space_id”是唯一的时,giix可能会在ActiveRecord类的rules()中添加一个验证规则。 These rules are checked before an ActiveRecord is saved and it will only save if all rules are okay. 在保存ActiveRecord之前检查这些规则,只有在所有规则都正常的情况下才会保存。 Read the Data Validation section of Definitive Guide for more information. 有关详细信息,请阅读“ 权威指南”的“ 数据验证”部分

From what I understand since Yii 1.1 composite primary keys are not longer supported with Gii, which is frustrating many developers. 根据我的理解,因为Yii不再支持Yii 1.1复合主键,这使许多开发人员感到沮丧。 There are other poorly documented alterations needed in your code aside from the returning an array as a primary key. 除了将数组作为主键返回之外,代码中还需要其他记录不完整的更改。

The best explanation I found was in this discussion in the Yii forum. 我发现的最佳解释是在Yii论坛的讨论中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM