Skip to content

Migrator

addReference()

addReference() — returns void

Available in: migration Category: Migration Functions

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.

NameTypeRequiredDefaultDescription
tablestringyesThe table name to perform the operation on
referenceNamestringyesThe reference table name to perform the operation on
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.