Skip to content

Model Configuration

hasOne()

hasOne() — returns void

Available in: model Category: Association Functions

Sets up a hasOne association between this model and the specified one.

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).
joinTypestringnoouterUse to set the join type when joining associated tables. Possible values are inner (for INNER JOIN) and outer (for LEFT OUTER JOIN).
dependentstringnofalseDefines how to handle dependent model objects when you delete an object from this model. delete / deleteAll deletes the record(s) (deleteAll bypasses object instantiation). remove / removeAll sets the forein key field(s) to NULL (removeAll bypasses object instantiation).
asstringno—Set this argument to declare a polymorphic hasOne association. The child model stores the parent type in a {as}Type column alongside the foreign key {as}Id.
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 have one profile. (The associated model's table, not the current one, should have the foreign key column.)
hasOne("profile");

// 2. Same as above but setting `joinType` to `inner`, meaning this model should always have a matching record in the `profiles` table.
hasOne(name="profile", joinType="inner");

// 3. Automatically delete the associated `profile` record whenever this object is deleted.
hasOne(name="profile", dependent="delete");

// 4. Declare a polymorphic `hasOne` association so that multiple models can each have one image via a shared interface.
hasOne(name="image", as="imageable");