Migrator
addForeignKey()
Signature
Section titled “Signature”addForeignKey() — returns void
Available in: migration
Category: Migration Functions
Description
Section titled “Description”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.
Parameters
Section titled “Parameters”| Name | Type | Required | Default | Description |
|---|---|---|---|---|
table | string | yes | — | The table name to perform the operation on |
referenceTable | string | yes | — | The reference table name to perform the operation on |
column | string | yes | — | The column name to perform the operation on |
referenceColumn | string | yes | — | The reference column name to perform the operation on |
Examples
Section titled “Examples”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.