Menu Close
    Hire us Request quote Reading list Switch to dark mode

    Add Foreign key in Magento2

    Here we are discussing to make a column to a foreign key in your table by installer.

    Add following code in your “InstallSchema.php” file:

    Here, “wk_child_table” is a name of foreign key table .

    “wk_main_table” is a name of parent table/reference table.

    “main_id” is a reference column name of “wk_main_table” table.

    “entity_id” is a foreign key column name of “wk_child_table” table.

    “ACTION_CASCADE” : is a type of action which executes on a matched row of child table when a parent table row get updated or deleted

    Here are list of types which can be add/define:

    1. ACTION_CASCADE: It automatically update or delete the matching child row(foreign key row) when parent table row get updated or deleted.
    2. ACTION_SET_NULL: It sets the value to null of foreign key column or columns  when parent table row get updated or deleted.
    3.  ACTION_NO_ACTION: When a parent table’s column get deleted or updated then there is no action is performed on child column.
    4. ACTION_RESTRICT: Rejects the update or delete operation, it means no changes happens when parent table row get deleted or updated. This action is used as default action.
    5. ACTION_SET_DEFAULT: it is working same as ACTION_SET_NULL, difference is it sets column’s default value when a parent row get update or delete.

    Note: Type of both the columns reference column and foreign key column should be same.

    After using this code foreign key will be added to your table’s column.

    Thank you.

    . . .

    Comment (1)

    Add Your Comment

  • Aaron McMillin
    What do you call the “addForeignKey” method on? And can you do this to modify the Customer model to add a new FK?
  • Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just received your message and our expert will get back to you shortly.
    Send Again