У меня есть простой юнит-тест:
$newItem = new Item;
$itemTitle = "New item 1";
$newItem->setAttributes(
array(
'part' => '0000',
'type_id' => 1,
'category_id' => 1,
'title' => $itemTitle,
'title_template' => '',
'color' => 'black',
'size' => 40,
'desc' => 'Test New Item 1',
)
);
$this->assertTrue($newItem->save(false));
Когда я запустил этот тест, я получил ошибку:
CDbException: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`wh_test`.`tbl_item`, CONSTRAINT `fk_goods_type` FOREIGN KEY (`type_id`) REFERENCES `tbl_type` (`id`) ON UPDATE CASCADE). The SQL statement executed was: INSERT INTO `tbl_item` (`part`, `type_id`, `category_id`, `title`, `title_template`, `color`, `size`, `desc`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7)
/var/www/yii/framework/db/CDbCommand.php:354
/var/www/yii/framework/db/ar/CActiveRecord.php:1014
/var/www/yii/framework/db/ar/CActiveRecord.php:787
/var/www/wh/wh/protected/tests/unit/ItemTest.php:18
Я пытаюсь вручную вставить его в базу данных, и все в порядке:
INSERT INTO `tbl_item` VALUES (0, '0000', 1, 1, 'New item 1', '', 'black', 40, 'Test New Item 1', NULL);
Что не так? Кажется, неправильные отношения, но я новичок Yii.
Вот соотношение () модели изделия:
return array(
'goods' => array(self::HAS_MANY, 'Goods', 'item_id'),
'type' => array(self::BELONGS_TO, 'Type', 'type_id'),
'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
'descTemplate' => array(self::BELONGS_TO, 'DescTemplate', 'desc_template_id'),
);
и SQL CREATE TABLE:
CREATE TABLE IF NOT EXISTS `wh`.`tbl_item` (
`id` INT NOT NULL AUTO_INCREMENT,
`part` VARCHAR(45) NOT NULL,
`type_id` INT NOT NULL,
`category_id` INT NOT NULL,
`title` VARCHAR(200) NOT NULL ,
`title_template` VARCHAR(200) NOT NULL ,
`color` VARCHAR(45) NOT NULL ,
`size` INT NOT NULL ,
`desc` TEXT NOT NULL ,
`desc_template_id` INT NULL ,
PRIMARY KEY (`id`),
CONSTRAINT `fk_goods_type`
FOREIGN KEY (`type_id` )
REFERENCES `wh`.`tbl_type` (`id` )
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT `fk_goods_category`
FOREIGN KEY (`category_id` )
REFERENCES `wh`.`tbl_category` (`id` )
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT `fk_goods_desc_template`
FOREIGN KEY (`desc_template_id`)
REFERENCES `wh`.`tbl_desc_template` (`id`)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE = InnoDB;