Relationships

Define relationships between your models

One-to-Many Relationship

A user can have many posts:

models/one-to-many.tstypescript
import { defineModel, DataTypes, RelationType } from "stabilize-orm";
const User = defineModel({
tableName: "users",
columns: {
id: { type: DataTypes.Integer },
name: { type: DataTypes.String, length: 255 },
},
relations: [
{
type: RelationType.OneToMany,
target: () => Post,
property: "posts",
foreignKey: "userId",
},
],
});
const Post = defineModel({
tableName: "posts",
columns: {
id: { type: DataTypes.Integer },
userId: { type: DataTypes.Integer, required: true },
title: { type: DataTypes.String, length: 255 },
},
relations: [
{
type: RelationType.ManyToOne,
target: () => User,
property: "user",
foreignKey: "userId",
},
],
});

One-to-One Relationship

A user has one profile:

models/one-to-one.tstypescript
const User = defineModel({
tableName: "users",
columns: {
id: { type: DataTypes.Integer },
email: { type: DataTypes.String, length: 100 },
},
relations: [
{
type: RelationType.OneToOne,
target: () => Profile,
property: "profile",
foreignKey: "userId",
},
],
});
const Profile = defineModel({
tableName: "profiles",
columns: {
id: { type: DataTypes.Integer },
userId: { type: DataTypes.Integer, required: true, unique: true },
bio: { type: DataTypes.Text },
},
});

Many-to-Many Relationship

Users can have many roles, and roles can belong to many users:

models/many-to-many.tstypescript
const User = defineModel({
tableName: "users",
columns: {
id: { type: DataTypes.Integer },
name: { type: DataTypes.String, length: 255 },
},
relations: [
{
type: RelationType.ManyToMany,
target: () => Role,
property: "roles",
through: "user_roles",
foreignKey: "userId",
otherKey: "roleId",
},
],
});
const Role = defineModel({
tableName: "roles",
columns: {
id: { type: DataTypes.Integer },
name: { type: DataTypes.String, length: 50 },
},
relations: [
{
type: RelationType.ManyToMany,
target: () => User,
property: "users",
through: "user_roles",
foreignKey: "roleId",
otherKey: "userId",
},
],
});

Querying with Relations

Load related data with your queries:

queries/with-relations.tstypescript
const userRepository = orm.getRepository(User);
// Load user with posts
const userWithPosts = await userRepository
.find()
.with("posts")
.where("id = ?", 1)
.first();
// Load user with posts and roles
const userWithRelations = await userRepository
.find()
.with(["posts", "roles"])
.where("id = ?", 1)
.first();