Yii Composite Primary Key Model

My main MySQL table is a collection of two 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 duplicate, but allows me to create rows on the same day or the same space_id.

However, in Yii, when using the new Object () and save (), he complains that the "space_id" must be unique.

I used "Giix" to generate the model, if that matters.

I tried adding this code to the model, but this did not help:

 public function primaryKey(){ return array('space_id', 'day'); } 
+4
source share
2 answers

Adding this code to the ActiveRecord class is OK, but not necessary, because Yii already has this information from your MySQL table declaration.

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

When Yii complains that "space_id" is unique, giix may have added a rule check rule () to its ActiveRecord class. These rules are checked before saving ActiveRecord, and this will be saved only if all the rules are in order. Read more in the Data Validation section of the Definition Guide .

+10
source

From what I understand, since Yii 1.1 composite primary keys are no longer supported by Gii, which disappoints many developers. There are other poorly documented changes in your code besides the returned array as the primary key.

The best explanation I found was in this discussion on the Yii forum.

0
source

Source: https://habr.com/ru/post/1392655/


All Articles