如何以编程方式向表添加外键?


22

我试图添加一组新表,并且试图添加外键来链接这些表。我在网上寻找addForeignKey()可以找到有关的信息,但找不到任何东西。

看着Varien_Db_Adapter_Interface::addForeignKey()Mage_Core_Model_Resource_Setup::getFkName()我想下面的设置我已经得到了正确

->addForeignKey(
     $installer->getFkName('namespace_module/shop', 'area_id', 'namespace_module/area','area_id'),
     $installer->getTable('namespace_module/shop'), 
     'area_id',
     $installer->getTable('namespace_module/area'), 
     'area_id',
     Varien_Db_Ddl_Table::ACTION_CASCADE, 
     Varien_Db_Ddl_Table::ACTION_CASCADE
)  

但是例外说不一样

Zend_Db_Exception Object
(
[_previous:Zend_Exception:private] => 
[message:protected] => Undefined column "shop_locator_shop"
[string:Exception:private] => 
[code:protected] => 0
[file:protected] => /Users/myname/Sites/site/www/lib/Varien/Db/Ddl/Table.php
[line:protected] => 450
[trace:Exception:private] => Array
    (
        [0] => Array
            (
                [file] => /Users/myname/Sites/site/www/app/code/local/Namespace/Module/sql/namespace_module_setup/install-0.1.0.php
                [line] => 110
                [function] => addForeignKey
                [class] => Varien_Db_Ddl_Table
                [type] => ->
                [args] => Array
                    (
                        [0] => FK_SHOP_LOCATOR_SHOP_AREA_ID_SHOP_LOCATOR_AREA_AREA_ID
                        [1] => shop_locator_shop
                        [2] => area_id
                        [3] => shop_locator_area
                        [4] => area_id
                        [5] => CASCADE
                        [6] => CASCADE
                    )

            )

基本上,我该如何向表中添加外键(我已添加了要实现的目标的屏幕截图)

数据库

Answers:


29

像这样尝试:

->addForeignKey(
     $installer->getFkName('namespace_module/shop', 'area_id', 'namespace_module/area','area_id'),
     'area_id',
     $installer->getTable('namespace_module/area'), 
     'area_id',
     Varien_Db_Ddl_Table::ACTION_CASCADE, 
     Varien_Db_Ddl_Table::ACTION_CASCADE
)  

我的代码的不同之处在于,我删除了下面的第一行getFkName
由于addForeignKey创建表时正在调用它,因此无需再次指定其名称。

作为一般规则使用:

->addForeignKey(
     $installer->getFkName('TABLE ALIAS', 'FK_FIELD', 'REF_TABLE_ALIAS','REF_TABLE_FIELD'),
     'CURRENT_TABLE_FIELD_NAME',
     $installer->getTable('REF_TABLE_ALIAS'), 
     'REF_TABLE_FIELD',
     Varien_Db_Ddl_Table::ACTION_CASCADE, 
     Varien_Db_Ddl_Table::ACTION_CASCADE
)  

[编辑]
您应该关注一下,Varien_Db_Ddl_Table::addForeignKey因为您正在的实例上使用它Varien_Db_Ddl_Table

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.