Has One

The HasOne relationship creates a one-to-one relationship between two models. A great example of this is a user has one profile.

Relationship models

Continuing with the user and the profile example. Following is the User model with the hasOne relationship.

import { column, BaseModel, hasOne, HasOne } from '@ioc:Adonis/Lucid/Orm'
import Profile from 'App/Models/Profile'

export default class User extends BaseModel {
  @hasOne(() => Profile)  public profile: HasOne<typeof Profile>}

The Profile model must have a foreign key column userId defined on it.

import { column, BaseModel } from '@ioc:Adonis/Lucid/Orm'

export default class Profile extends BaseModel {
  @column()  public userId: number}

Custom foreign key

By default, the foreignKey is the camelCase representation of the parent model name and its primary key.

Parent Model NamePrimary KeyForeign Key

However, you can also define a custom foreign key.

@hasOne(() => Profile, {
  foreignKey: 'profileUserId',
public profile: HasOne<typeof Profile>

Custom local key

The local key is always the primary key of the parent model, but can be defined explicitly.

@hasOne(() => Profile, {
  localKey: 'uuid',
  foreignKey: 'profileUserId',
public profile: HasOne<typeof Profile>

Table structure

Following is an example table describing the relationship at the database level.

Lucid models doesn't rely on the database level foreign key constraint. It just want the columns to be present and must be of same data types.

What's next?

The preloading and persistance API for a has one relationship is already covered in the introduction guide, we recommend reading all of the the sections.