SlintORM
Docsnpm

@relation / @relationship

Declares relationships between models. Both @relation and @relationship are accepted interchangeably. See the Relations section for full concept docs.

Syntax

syntax
@relation <kind>:<Model>[;foreignKey:<col>][;relatedKey:<col>][;through:<table>][;onDelete:CASCADE|SET NULL]

One-to-Many

src/interfaces.ts
interface User {
  // @relation onetomany:Post;foreignKey:userId
  posts?: Post[];
}
interface Post {
  userId: number;
  // @relation manytoone:User;foreignKey:userId
  user?: User;
}

One-to-One

src/interfaces.ts
interface User {
  // @relationship onetoone:Profile;foreignKey:userId
  profile?: Profile;
}
interface Profile {
  // @unique
  userId: number;
  // @relationship onetoone:User;foreignKey:userId;onDelete:CASCADE
  user?: User;
}

Many-to-Many

src/interfaces.ts
interface User {
  // @relation manytomany:Team;through:team_members;foreignKey:userId;relatedKey:teamId
  teams?: Team[];
}
interface Team {
  // @relation manytomany:User;through:team_members;foreignKey:teamId;relatedKey:userId
  members?: User[];
}
// Pivot table team_members(userId, teamId) auto-created by migrate()

Relation Shortcuts

src/interfaces.ts
// @belongsTo:Model — shortcut for manytoone
// @belongsTo:User
user?: User;

// @hasMany:Model — shortcut for onetomany
// @hasMany:Post
posts?: Post[];

// @hasOne:Model — shortcut for onetoone
// @hasOne:Profile
profile?: Profile;

// @belongsToMany:Model — shortcut for manytomany
// @belongsToMany:Team
teams?: Team[];

Parameters

ParamRequiredDescription
foreignKeyYesColumn on the child/many side
relatedKeyMany-to-manyColumn on the related side (default: id)
throughMany-to-manyPivot table name
onDeleteNoCASCADE or SET NULL on foreign key

Errors

ErrorCauseFix
Post.user -> User has no inverse relation for PostOne side of a relation is missing the inverse annotationAdd @relation manytoone:Post on the inverse side
Unknown relation targetModel name doesn't match any known interfaceCheck the model name spelling in the annotation
Duplicate interface "User" foundMultiple models have the same name in different filesUse unique interface names across your project

Conventions

See also