How to add a foreign key with onUpdate Cascade in an M2 installer script?
質問
I want to add a table with a foreign key in an installer script. The foreign key should have
ONDELETE CASCADE and ONUPDATE CASCADE set, - but the ->addForeignKey method supports only the ONDELETE one.
How can I set the ONUPDATE CASCADE setting?
My code:
$table = $installer->getConnection()
->newTable($installer->getTable('my_new_table'))
->addColumn(
'entity_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
11,
['identity' => true, 'unsigned' => false, 'nullable' => false, 'primary' => true],
'Entity ID'
)
->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
5,
['nullable' => false, 'unsigned' => true, 'primary' => true],
'Store ID'
)
->addForeignKey(
'fk_entity_store_id',
'entity_id',
'my_new_table',
'entity_id',
\Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
);
解決
The ONUPDATE CASCADE is executed, when the row id of a record is changed. This should not happen in Magento at all, as the ids are unique and persistent over their lifetime. Actions like the change of a row id should be prevented from occurring.
Luckily, this is exactly, what omitting an ONUPDATE clause does:
RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause. (Source: https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html:)
The "missing" parameter has therefore most likely been omitted by design.