2011-08-25 125 views
0

我有表及其SQL是如下:外鍵約束失敗,Zend_Db_Table類

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,約束salesrecord_ibfk_1外鍵(itemID)參考文獻itemitemID))

回答

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'。

+0

謝謝Devart,它的工作原理! –