Skip to content

Model Configuration

belongsTo()

belongsTo() — returns void

Available in: model Category: Association Functions

Sets up a belongsTo association between this model and the specified one. Use this association when this model contains a foreign key referencing another model.

NameTypeRequiredDefaultDescription
namestringyes—Gives the association a name that you refer to when working with the association (in the include argument to findAll, to name one example).
modelNamestringno—Name of associated model (usually not needed if you follow Wheels conventions because the model name will be deduced from the name argument).
foreignKeystringno—Foreign key property name (usually not needed if you follow Wheels conventions since the foreign key name will be deduced from the name argument).
joinKeystringno—Column name to join to if not the primary key (usually not needed if you follow Wheels conventions since the join key will be the table’s primary key/keys).
joinTypestringnoinnerUse to set the join type when joining associated tables. Possible values are inner (for INNER JOIN) and outer (for LEFT OUTER JOIN).
polymorphicbooleannofalseSet to true to declare a polymorphic belongsTo association. The foreign key defaults to {name}Id and a {name}Type column is used to store the owning model name at runtime.
foreignTypestringno—The column that stores the owning model’s name in a polymorphic association. Defaults to {name}Type. Pass it, with foreignKey, when the columns are named differently, e.g. notable_type / notable_id as t.references(polymorphic = true) writes them when useUnderscoreReferenceColumns is on.
// 1. Specify that instances of this model belong to an author.
// (The table for this model should have a foreign key column, typically named `authorId`.)
belongsTo("author");

// 2. Override naming conventions by specifying `modelName` and `foreignKey` explicitly.
belongsTo(name="bookWriter", modelName="author", foreignKey="authorId");

// 3. Use a LEFT OUTER JOIN instead of the default INNER JOIN when including this association.
belongsTo(name="category", joinType="outer");

// 4. Declare a polymorphic belongsTo association (e.g. a Comment that can belong to a Post or a Photo).
// Wheels will look for `commentableId` and `commentableType` columns on the comments table.
belongsTo(name="commentable", polymorphic=true);