Skip to content

Migrator

addForeignKey()

addForeignKey() — returns void

Available in: migration Category: Migration Functions

Add a foreign key constraint to the database, using the reference name that was used to create it Only available in a migration CFC

NameTypeRequiredDefaultDescription
tablestringyes—The table name to perform the operation on
referenceTablestringyes—The reference table name to perform the operation on
columnstringno—The column name to perform the operation on
columnNamestringno—Modern alias for column (consistent with the rest of the migrator surface).
referenceColumnstringyes—The reference column name to perform the operation on
// 1. Add a foreign key from orders.customerId to customers.id
addForeignKey(
    table="orders",
    referenceTable="customers",
    column="customerId",
    referenceColumn="id"
);

// 2. Add a foreign key from comments.postId to posts.id
addForeignKey(
    table="comments",
    referenceTable="posts",
    column="postId",
    referenceColumn="id"
);

// 3. Use addForeignKey in a migration's up() and remove it in down()
// In your migration CFC:
//
// public void function up() {
//     addForeignKey(
//         table="order_items",
//         referenceTable="orders",
//         column="orderId",
//         referenceColumn="id"
//     );
// }
//
// public void function down() {
//     dropForeignKey(table="order_items", keyName="FK_order_items_orders");
// }