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

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

问题描述

我的 MySQL 表的主表由 2 列组成:space_id (INTEGER) 和 day (DATE).

创建表`ck_space_calendar_cache`(`space_id` int(11) 非空,`day` 日期不为空,`available` tinyint(1) 无符号 NOT NULL DEFAULT '0',`价格`十进制(12,2)默认为空,`offer` varchar(45) 默认为空,`presale_date` 日期默认为空,`presale_price` 十进制(12,2)默认为空,`value_x` int(11) 默认为空,`value_y` int(11) 默认为空,PRIMARY KEY (`space_id`,`day`),KEY`空间`(`space_id`),约束`space`外键(`space_id`)引用`ck_space`(`id`)在更新时删除级联无操作) 引擎=InnoDB 默认字符集=utf8;

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

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

如果重要的话,我使用Giix"来生成模型.

我尝试将此代码添加到模型中,但没有帮助:

公共函数primaryKey(){return array('space_id', 'day');}

解决方案

将此代码添加到您的 ActiveRecord 类是可以的,但应该没有必要,因为 Yii 已经从您的 MySQL 表声明中获得了该信息.

 公共函数primaryKey(){return array('space_id', 'day');}

当 Yii 抱怨space_id"是唯一的时,giix 可能在您的 ActiveRecord 类中的 rules() 中添加了验证规则.在保存 ActiveRecord 之前检查这些规则,并且只有在所有规则都正常时才会保存.阅读权威指南的数据验证部分了解更多信息.>

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;

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.

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

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');
        }

解决方案

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');
    }

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天全站免登陆