具有复合主键的Yii模型 [英] Yii Model with composite primary key

查看:158
本文介绍了具有复合主键的Yii模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL表的主要是2列的组合:space_id(INTEGER)和day(DATE)。

My MySQL table's primary is a composite of 2 columns: space_id (INTEGER) and 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;

它在原始SQL中工作正常,如果我尝试创建副本,它会抱怨,但让我创建行在同一天或相同的space_id。

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.

然而,在Yii中使用新的Object()和save()时,它会抱怨好像space_id必须是唯一的。

However, in Yii when using new Object() and save(), it complains as if "space_id" has to be unique.

如果重要的话,我使用Giix生成模型。

I used "Giix" to generate the model if it matters.

我试图添加这个代码到模型,但它没有帮助:

I tried to add this code to the model, but it didn't help:

public function primaryKey(){
            return array('space_id', 'day');
        }


推荐答案

将此代码添加到ActiveRecord class是可以的,但是不应该是必要的,因为Yii已经从你的MySQL表声明中获得了这些信息。

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.

    public function primaryKey(){
       return array('space_id', 'day');
    }

当Yii抱怨space_id是唯一的时候,giix可能添加了一个验证规则到ActiveRecord类中的rules()。在保存ActiveRecord之前检查这些规则,只有在所有规则都正常的情况下才会保存。有关详细信息,请阅读权威指南的数据验证部分

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 Guide for more information.

这篇关于具有复合主键的Yii模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆