Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Relations

Many-to-One and One-to-Many Relations

Model one-to-many relations with TypeORM decorators and Sequelize hasMany and belongsTo, understand foreign keys and the owning side, and join tables with a runnable stand-in.

An author has many posts; each post belongs to one author. This is the most common relation in any database, and both ORMs model it the same way underneath: the many side holds a foreign key column that points at the one side's primary key.

Library code is read-only; the stand-ins use SQLite and a hand-written loader to show the foreign key at work.

The database view

erDiagram
  AUTHOR ||--o{ POST : writes
  AUTHOR {
    int id PK
    string name
  }
  POST {
    int id PK
    string title
    int author_id FK
  }

One author row, many post rows. Only post stores the key (author_id).

TypeORM: both sides

TypeScript
@Entity()
export class Author {
  @PrimaryGeneratedColumn() id!: number;
  @Column() name!: string;

  @OneToMany(() => Post, (post) => post.author)
  posts!: Post[];
}

@Entity()
export class Post {
  @PrimaryGeneratedColumn() id!: number;
  @Column() title!: string;

  @ManyToOne(() => Author, (author) => author.posts, { onDelete: "CASCADE", nullable: false })
  @JoinColumn({ name: "author_id" })
  author!: Author;
}
  • @ManyToOne is the owning side: the foreign key column lives on this entity. @OneToMany cannot exist without a matching @ManyToOne, and it does not add a column.
  • The arrow functions (() => Post) avoid circular-import problems.
  • @JoinColumn is optional for many-to-one but lets you name the column. To read the key without loading the author, add @Column() authorId!: number; next to the relation.
TypeScript
const author = await authors.save({ name: "Ana" });
await posts.save({ title: "Hello", author });             // sets author_id
const withPosts = await authors.find({ relations: { posts: true } });

Sequelize: associations

Sequelize defines relations by calling association methods after models are initialized.

TypeScript
Author.hasMany(Post, { foreignKey: { name: "authorId", allowNull: false }, as: "posts", onDelete: "CASCADE" });
Post.belongsTo(Author, { foreignKey: "authorId", as: "author" });

hasMany adds the foreign key to the target (Post.authorId) and gives the author helpers such as author.getPosts(), author.createPost(), author.addPost() and author.countPosts(). belongsTo gives the post post.getAuthor() and post.setAuthor(). Declare both sides so queries work in both directions.

TypeScript
const author = await Author.create({ name: "Ana" });
await author.createPost({ title: "Hello" });                // sets authorId
const withPosts = await Author.findAll({ include: [{ model: Post, as: "posts" }] });

The two sides side by side

Idea TypeORM Sequelize
Many side (holds FK) @ManyToOne belongsTo
One side @OneToMany hasMany
FK column name @JoinColumn({ name }) foreignKey
Delete behaviour onDelete: "CASCADE" onDelete: "CASCADE"
Load related rows relations: { posts: true } include: [Post]

Foreign keys in action

A foreign key makes the database refuse orphans. This stand-in switches on PRAGMA foreign_keys (off by default in SQLite, on in PostgreSQL and MySQL/InnoDB) and tries to break the rule.

Node.js Foreign key constraint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Loading the relation

relations and include both turn into a JOIN (or extra queries). The important thing is what shape you get back: each author with a posts array. This stand-in does the loading by hand, in two queries, which is how some ORM strategies work internally.

Node.js Load authors with posts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two queries for any number of authors, not one per author: this is the cure for the N+1 problem covered in the performance chapter.

Design choices

  • Nullable or not: if every post must have an author, make the key NOT NULL (nullable: false / allowNull: false).
  • Delete behaviour: CASCADE removes children, SET NULL keeps them with no parent, RESTRICT blocks deleting a parent that still has children. Choose per relation; CASCADE is convenient and dangerous.
  • Index the foreign key: PostgreSQL does not index FK columns automatically. Add @Index() (TypeORM) or an indexes entry (Sequelize), because you will filter and join on it constantly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which table holds the foreign key in an author-has-many-posts relation?

    The many side stores the key that points to the one side.
  2. 2. Which TypeORM decorator is the owning side of a one-to-many relation?

    @ManyToOne is where the foreign key column lives; @OneToMany is the inverse side.
  3. 3. In Sequelize, how do you make both directions work?

    Declaring both sides gives you include and helper methods from each model.
  4. 4. What does ON DELETE CASCADE do?

    The database removes dependent rows automatically.

Summary

  • One-to-many means the many side stores a foreign key to the one side.
  • TypeORM: @ManyToOne (owning, FK) plus @OneToMany (inverse); Sequelize: belongsTo plus hasMany.
  • Load related rows with relations or include; ORMs can do it with JOINs or extra queries.
  • Decide nullability and delete behaviour deliberately, and index the foreign key.
  • Foreign keys make the database enforce integrity.

Next: One-to-One Relations