Skip to content

Migrator

addForeignKey()

addForeignKey() — returns void

Available in: migration Category: Migration Functions

Adds a foreign key constraint between two tables. This ensures that values in one table’s column must exist in the referenced column of another table, enforcing referential integrity. This function is only available inside a migration CFC and is part of the Wheels migrator API.

NameTypeRequiredDefaultDescription
tablestringyesThe table name to perform the operation on
referenceTablestringyesThe reference table name to perform the operation on
columnstringyesThe column name to perform the operation on
referenceColumnstringyesThe reference column name to perform the operation on
1. Basic foreign key
addForeignKey(
    table="orders",
    referenceTable="users",
    column="userId",
    referenceColumn="id"
);

Ensures that every orders.userId must exist in users.id.

2. Foreign key for many-to-one relation
addForeignKey(
    table="comments",
    referenceTable="posts",
    column="postId",
    referenceColumn="id"
);

Ensures each comment is linked to a valid post.

3. Foreign key with a custom reference column
addForeignKey(
    table="invoices",
    referenceTable="customers",
    column="customerCode",
    referenceColumn="code"
);

Links invoices.customerCode to customers.code instead of a numeric ID.

4. Multiple foreign keys in one migration
// In migration
addForeignKey(
    table="enrollments",
    referenceTable="students",
    column="studentId",
    referenceColumn="id"
);

addForeignKey(
    table="enrollments",
    referenceTable="courses",
    column="courseId",
    referenceColumn="id"
);

The enrollments table is linked to both students and courses.