Yii Model with composite primary key

22,771

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.

Share:
22,771
Nathan H
Author by

Nathan H

Soluto #SOreadytohelp

Updated on July 09, 2022

Comments

  • Nathan H
    Nathan H almost 2 years

    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');
            }
    
  • Nathan H
    Nathan H almost 12 years
    giix was doing some validation