外键约束因Zend_Db_Table而失败

时间:2011-08-25 04:31:59

标签: mysql sql zend-framework zend-db zend-db-table

我必须使用表格,他们的SQL如下:

CREATE TABLE item (
itemID INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
name VARCHAR(100) NOT NULL,
price FLOAT NOT NULL,
stock INTEGER NOT NULL
) ENGINE = InnoDB;


CREATE TABLE salesrecord (
recordID INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
itemID INT UNSIGNED NOT NULL,
recordDate DATE NOT NULL,
FOREIGN KEY (itemID) REFERENCES item (itemID)
) ENGINE = InnoDB;

这是我的Zend_Db_Table具体课程:

<?php
class Store_Model_Items extends Zend_Db_Table_Abstract
{
  protected $_name = 'item';
  protected $_rowClass = 'Store_Model_Item';
  protected $_dependTables = array('Store_Model_SalesRecords');
}


<?php
class Store_Model_SalesRecords extends Zend_Db_Table_Abstract
{
  protected $_name = 'salesrecord';
  protected $_referenceMap = array(
    'Item' => array(
        'columns' => array('itemID'),
        'refTableClass' => 'Store_Model_Items',
        'refColumns' => array('itemID'),
        'onDelete' => self::CASCADE
    )
  );
} 

当我尝试删除项目表中的一行时, 我收到这条消息:

SQLSTATE [HY000]:常规错误:1451无法删除或更新父行:外键约束失败(newstore/salesrecord,CONSTRAINT salesrecord_ibfk_1 FOREIGN KEY(itemID)REFERENCES {{ 1}}(item))

1 个答案:

答案 0 :(得分:0)

如果要从父表中删除记录,首先应删除子表中的相关记录。您还可以添加ON DELETE CASCADE检查,它将帮助自动删除子表中的相关记录。尝试以这种方式重建你的FK -

ALTER TABLE salesrecord
  DROP FOREIGN KEY salesrecord_ibfk_1; -- change FK name here!

ALTER TABLE salesrecord
  ADD CONSTRAINT salesrecord_ibfk_1 FOREIGN KEY (itemID)
    REFERENCES item(itemID) ON DELETE CASCADE;

使用实际FK名称更改'salesrecord_ibfk_1'。