2

I have 2 table. I want to createForeignKey. I have my code:

if(version_compare($context->getVersion(), '1.2.0', '<')) {
        $installer->getConnection()->addForeignKey(
            $installer->getFkName('course_courses', 'courses_id', $installer->getTable('course_participant'), 'courses_id'),
            $installer->getTable('course_courses'),
            'courses_id',
            $installer->getTable('course_participant'),
            'courses_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_NO_ACTION
        );
    }

enter image description hereenter image description here

Please help me!

1
  • In Magento 2.3, Use declarative schema instead of using install data script.
    – Sumit
    Jun 8, 2020 at 6:54

3 Answers 3

2

Try this:

->addForeignKey(
      $installer->getFkName('<ChildTable>', 'entity_id', '<ParentTable>', 'entity_id'),
      'entity_id',
      $installer->getTable('<ParentTable>'),
      'entity_id',
      \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
)

Note: Both table has same field and set primary key to parent table.

You are adding Foreign key to wrong table, You can not set customer_grid_flat table's entity_id as foreign key until you set primary key to customer_entity_varchar table's entity_id.

And read more information:-

Magento 2 How to add foreign key in update schema

Hope this help you

Thanks ...

1
  • Thank for your help!
    – Tom
    Jun 8, 2020 at 6:28
4

Try below code

if(version_compare($context->getVersion(), '1.2.0', '<')) {
    $installer->getConnection()->addForeignKey(
        $installer->getFkName('course_courses', 'courses_id','course_participant','courses_id'),
        $installer->getTable('course_courses'),
        'courses_id',
        $installer->getTable('course_participant'),
        'courses_id',
        \Magento\Framework\DB\Ddl\Table::ACTION_NO_ACTION
    );
}

Check if setup Version in your module.xml file with tag setup_version = 1.2.0 ? And in your database check if setup_module search your modulename entry have vesion less than 1.2.0 ?than only it will run upgradeschema file.

0

Your code is correct. But the primary key of your parent table is 'id'.

if(version_compare($context->getVersion(), '1.2.0', '<')) {
    $installer->getConnection()->addForeignKey(
        $installer->getFkName('course_participant', 'courses_id', $installer->getTable('course_courses'), 'id'),
        'course_participant',
        'courses_id',
        $installer->getTable('course_courses'),
        'id',
        \Magento\Framework\DB\Ddl\Table::ACTION_NO_ACTION
    );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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