Skip to main content

through associations

Both HasOne and HasMany associations have recursively-nested through support built-in, enabling you to bring nested associations out of their nested context and into the parent model's domain:

export default class CommentReply extends Dream {
@deco.BelongsTo('Comment')
public comment: Comment

@deco.HasOne('User', { through: 'comment' })
public user: User
}

Traveling through other "through" associations

Dream permits you to travel through other "through" associations, which can simplify modeling:

class User extends ApplicationModel {
@deco.HasMany('Pet')
public pets: Pet[]

@deco.HasMany('Collar', { through: 'pets' })
public collars: Collar[]

@deco.HasMany('NameTag', { through: 'collars' })
public nameTags: NameTag[]
}

const user = await User.preload('nameTags').firstOrFail()
user.nameTags
// [NameTag{}, NameTag{}, ...]

Source

In some cases, the association name on the base model may be different than the association name on the child model. In these cases, you can specify which association name to travel through on the associated model by specifying the source option:

class User extends ApplicationModel {
@deco.HasMany('Pet')
public pets: Pet[]

@deco.HasMany('Collar', { through: 'pets', source: 'collars' })
public petCollars: Collar[]
}