0

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?

1

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
);
  • Still getting the same error sir ( I replace $installer with $setup ) – sayou Apr 25 at 17:36
  • Check updated answer, working fine with 2.3. – Sohel Rana Apr 25 at 17:46
  • It's work sir, thanks a lot for your help, I think the problem was on the column configuration – sayou Apr 26 at 8:33
  • Sir, do you advise me to use this method, Or adding a new attribute using EAV ? – sayou Apr 26 at 10:17
  • 1
    For EAV use, upgrade data, not schema – Sohel Rana Apr 26 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.