Add foreign key on UpgradeSchema return “Foreign key constraint is incorrectly formed”?
-
27-02-2021 - |
Question
I want to add a new attribute to catalog_product_website
table named id_admin_user
to make relation with admin_user
table.
PS: I want to do that to save the ID of the admin user who added a product.
So, I create an UpgradeSchema
with this code
$setup->getConnection()->addColumn(
$setup->getTable('catalog_product_website'),
'id_admin_user',
[
'type' => Table::TYPE_INTEGER,
'size' => null,
'nullable' => false,
'comment' => 'ID ADMIN USER'
]
);
$setup->getConnection()->addForeignKey(
$setup->getFkName(
'catalog_product_website',
'id_admin_user',
'admin_user',
'user_id'
),
$setup->getTable('catalog_product_website'),
'id_admin_user',
$setup->getTable('admin_user'),
'user_id',
Table::ACTION_CASCADE
);
But when I execute the setup:upgrade
I get this error
SQLSTATE[HY000]: General error: 1005 Can't create table `magento_test`.`#sql-357_165b` (errno: 150 "Foreign key constraint is incorrectly formed")
is there any solution?
Solution
In your code, setup should $setup. Check following code:
$setup->getConnection()->addForeignKey(
$setup->getFkName(
'catalog_product_website',
'id_admin_user',
'admin_user',
'user_id'
),
$setup->getTable('catalog_product_website'),
'id_admin_user',
$installer->getTable('admin_user'),
'user_id',
Table::ACTION_CASCADE
);
[Update]
Try following way:
$setup->getConnection()->addColumn(
$setup->getTable('catalog_product_website'),
'id_admin_user',
[
'type' => Table::TYPE_INTEGER,
'size' => null,
'nullable' => false,
'unsigned' => true,
'comment' => 'ID ADMIN USER'
]
);
$setup->getConnection()->addForeignKey(
$setup->getFkName(
'catalog_product_website',
'id_admin_user',
'admin_user',
'user_id'
),
$setup->getTable('catalog_product_website'),
'id_admin_user',
$setup->getTable('admin_user'),
'user_id',
Table::ACTION_CASCADE
);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange