Migrator
addReference()
Signature
Section titled “Signature”addReference() — returns void
Available in: migration
Category: Migration Functions
Description
Section titled “Description”Adds a reference column and a foreign key constraint to a table in one step. This is a shortcut for creating an integer column (e.g., userId) and then linking it to another table using a foreign key. 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 |
referenceName | string | yes | — | The reference table name to perform the operation on |
Examples
Section titled “Examples”1. Add a user reference to orders
addReference(
table="orders",
referenceName="users"
);
Adds a userId column to orders and creates a foreign key to users.id.
2. Add a post reference to comments
addReference(
table="comments",
referenceName="posts"
);
Creates a postId column on comments and links it to posts.id.
3. Add references to multiple tables
addReference(table="enrollments", referenceName="students");
addReference(table="enrollments", referenceName="courses");
Adds both studentId and courseId to enrollments with foreign keys to students and courses.
4. Composite example (reference + other fields)
addColumn(table="votes", columnType="boolean", columnName="upvote", default=1);
addReference(table="votes", referenceName="users");
addReference(table="votes", referenceName="posts");
Builds a votes table that connects users and posts with foreign keys.