Yii - 插入时AR和FK出错

时间:2012-03-07 10:15:07

标签: activerecord foreign-keys yii

我有简单的单元测试:

    $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:

 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; 

1 个答案:

答案 0 :(得分:0)

测试数据库存在问题。我已将数据与工作数据库同步,并且所有测试都已通过。