Skip to main content

Model Relationship

Defining a Model with Relation

In this section, we will explore how to create a model that incorporates relationships with other models. By using decorators such as ManyToOne and JoinColumn decorators, we can establish connections between different entities, enabling efficient data management and retrieval in our application. This approach helps to maintain data integrity and allows for more complex queries and operations.

Here is the code sample:

models/books.ts

import { Users } from "./user";
import {
Model,
ManyToOne,
JoinColumn,
Column,
NullColumn,
NumericColumn,
PrimaryKeyColumn,
TableModel,
TextColumn,
} from "alapa";

@TableModel()
export class Books extends Model {
@PrimaryKeyColumn()
id: number;

@Column()
title: string;

@JoinColumn({ name: "user" })
@ManyToOne((type) => Users, { onDelete: "CASCADE" })
user: Users;

@NullColumn()
author: string;

@NumericColumn()
year: number;

@TextColumn()
description: string;
}

Using the Model

Create a new record

import { Books } from "models/books";
import { Users } from "models/users";

const user = Users.findOneBy({ id: 1 });

if (!user) return;

book.title = req.body.title;
book.author = req.body.author;
book.year = req.body.year;
book.description = req.body.description;
book.user = user;

await book.save(); // save to database

See Resourceful Routing for more examples of how to perform CRUD operations.