【发布时间】:2012-03-07 10:15:06
【问题描述】:
我有简单的单元测试:
$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 新手。 这是 Item 模型的一个relatioins():
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 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;
【问题讨论】:
-
您能说出您的 tbl_type 表中存在哪些行吗?似乎没有 id 为 1 的行。
-
我在执行单元测试之前添加了一个测试行(id:1, name:test)
-
好的。我看到您在设置属性时没有传递表的主键(id);您也没有将 id 声明为自动增量。如果您将 id 声明为自动增量,我认为您的问题应该解决。在此之前,您可以通过在 setAttributes 方法中设置 id 来检查这是否是问题。
-
我尝试调用 setAttributes() 并声明 id 但没有更改,并且错误消息中没有
id字段。外键表很简单,如 table(id,name)。
标签: activerecord foreign-keys yii