TypeORM Many to One Relationship: A Guide for Beginners (2024)

**TypeORM Many to One Relationships**

In object-oriented programming, a many-to-one relationship is a relationship between two classes where one class has multiple instances of the other class. For example, a company can have many employees, and an employee can only work for one company.

In TypeORM, you can define many-to-one relationships using the `@ManyToOne` decorator. The `@ManyToOne` decorator takes two arguments: the name of the foreign key column on the child table, and the name of the entity that the child table refers to.

For example, the following code defines a many-to-one relationship between the `Company` and `Employee` entities:

typescript
@Entity()
export class Company {
@Id()
id: number;

@Column()
name: string;

@OneToMany(type => Employee, employee => employee.company)
employees: Employee[];
}

@Entity()
export class Employee {
@Id()
id: number;

@Column()
name: string;

@ManyToOne(type => Company, company => company.employees)
company: Company;
}

This code defines two columns on the `Company` table: `id` and `name`. It also defines a one-to-many relationship between the `Company` and `Employee` entities. The `employees` property on the `Company` entity is a collection of `Employee` objects. The `company` property on the `Employee` entity is a reference to the `Company` object that the employee belongs to.

When you create a new `Company` object, you can pass an array of `Employee` objects to the `employees` property. When you create a new `Employee` object, you can pass a reference to the `Company` object that the employee belongs to.

TypeORM will automatically create the necessary database tables and relationships when you run the `typeorm migration` command.

For more information on many-to-one relationships in TypeORM, please refer to the [TypeORM documentation](https://typeorm.io/docs/many-to-one-relationships/).

PropertyTypeDescription
targetEntitystringThe name of the entity that this relation belongs to.
mappedBystringThe name of the property on the target entity that this relation is mapped to.
inversedBystringThe name of the property on this entity that is the inverse of this relation.

****

In this tutorial, you will learn how to create a many-to-one relationship in TypeORM. We will use the following entities to demonstrate the relationship:

  • `User`
  • `Order`

The `User` entity will have a one-to-many relationship with the `Order` entity. This means that one `User` can have many `Order`s, and each `Order` can be associated with only one `User`.

**What is a Many-to-One Relationship in TypeORM?**

A many-to-one relationship is a type of association between two entities in a database, where one entity can have many instances of the other entity. For example, a `User` entity can have many `Order` entities.

In TypeORM, you can create a many-to-one relationship by using the `@ManyToOne` decorator. The `@ManyToOne` decorator takes two arguments:

  • The name of the foreign key column on the child entity.
  • The name of the entity that the child entity is related to.

For example, the following code creates a many-to-one relationship between the `User` and `Order` entities:

typescript
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@OneToMany(type => Order, order => order.user)
orders: Order[];
}

@Entity()
export class Order {
@PrimaryGeneratedColumn()
id: number;

@Column()
total: number;

@ManyToOne(type => User, user => user.orders)
user: User;
}

In this code, the `@OneToMany` decorator on the `User` entity defines the relationship between the `User` and `Order` entities. The `@ManyToOne` decorator on the `Order` entity defines the inverse relationship.

**How to Create a Many-to-One Relationship in TypeORM?**

To create a many-to-one relationship in TypeORM, you can use the following steps:

1. Create the entities that will be involved in the relationship.
2. Define the relationship between the entities using the `@ManyToOne` and `@OneToMany` decorators.
3. Migrate the database schema.
4. Create instances of the entities and establish the relationship between them.

We will now create a many-to-one relationship between the `User` and `Order` entities using the following steps:

1. Create the `User` and `Order` entities.

typescript
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@OneToMany(type => Order, order => order.user)
orders: Order[];
}

@Entity()
export class Order {
@PrimaryGeneratedColumn()
id: number;

@Column()
total: number;

@ManyToOne(type => User, user => user.orders)
user: User;
}

2. Define the relationship between the entities using the `@ManyToOne` and `@OneToMany` decorators.

The `@ManyToOne` decorator on the `User` entity defines the relationship between the `User` and `Order` entities. The `@OneToMany` decorator on the `Order` entity defines the inverse relationship.

typescript
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@OneToMany(type => Order, order => order.user)
orders: Order[];
}

@Entity()
export class Order {
@PrimaryGeneratedColumn()
id: number;

@Column()
total: number;

@ManyToOne(type => User, user => user.orders)
user: User;
}

3. Migrate the database schema.

To migrate the database schema, you can use the following command:

npx typeorm migration:run

This command will create the necessary tables and columns in the database.

4. Create instances of the entities and establish the relationship between them.

To create instances of the entities, you can use the following code:

typescript
const user =

3. Define the relationship in your entity models

To define the relationship between two entities in TypeORM, you need to add the `@ManyToOne` decorator to the property of the entity that will be the “many” side of the relationship. For example, if you have a `User` entity and a `Post` entity, you would add the `@ManyToOne` decorator to the `posts` property of the `User` entity:

typescript
import { Entity, Column, ManyToOne } from “typeorm”;

@Entity()
export class User {
@Column({ type: “int”, primaryKey: true })
id: number;

@Column({ type: “string”, nullable: false })
name: string;

@ManyToOne(type => Post)
posts: Post[];
}

The `@ManyToOne` decorator takes a type argument, which specifies the type of the entity that the `posts` property will be referencing. In this case, the `posts` property will be referencing `Post` entities.

You can also specify the name of the foreign key that will be used to link the two entities together. By default, the foreign key will be named `_id`, but you can override this by specifying the `foreignKeyName` property of the `@ManyToOne` decorator:

typescript
@Entity()
export class User {
@Column({ type: “int”, primaryKey: true })
id: number;

@Column({ type: “string”, nullable: false })
name: string;

@ManyToOne(type => Post, { foreignKeyName: “user_id” })
posts: Post[];
}

4. Define the foreign key in your database

Once you have defined the relationship between two entities in your entity models, you need to define the foreign key in your database. To do this, you need to add a foreign key constraint to the table for the “many” side of the relationship. For example, if you have a `users` table and a `posts` table, you would add a foreign key constraint to the `posts` table to reference the `id` column of the `users` table:

sql
ALTER TABLE posts
ADD CONSTRAINT fk_posts_users_id FOREIGN KEY (user_id) REFERENCES users (id);

The `fk_posts_users_id` constraint specifies that the `user_id` column in the `posts` table references the `id` column in the `users` table. This ensures that each `post` record has a corresponding `user` record.

In this tutorial, you learned how to define a many-to-one relationship between two entities in TypeORM. You learned how to define the relationship in your entity models and how to define the foreign key in your database.

By following these steps, you can easily create many-to-one relationships between your entities in TypeORM.

Q: What is a many-to-one relationship in TypeORM?

A many-to-one relationship is a type of relationship between two entities where one entity can have multiple instances of the other entity. For example, a `Post` entity can have many `Comment` entities.

Q: How do I create a many-to-one relationship in TypeORM?

To create a many-to-one relationship in TypeORM, you can use the `@ManyToOne` decorator. For example:

typescript
@Entity()
class Post {
@PrimaryGeneratedColumn()
id: number;

@Column()
title: string;

@ManyToOne(type => Comment, comment => comment.post)
comments: Comment[];
}

@Entity()
class Comment {
@PrimaryGeneratedColumn()
id: number;

@Column()
content: string;

@ManyToOne(type => Post, post => post.comments)
post: Post;
}

Q: How do I access the related entity in a many-to-one relationship?

To access the related entity in a many-to-one relationship, you can use the `get()` method. For example:

typescript
const post = await Post.findOne({ title: ‘My First Post’ });
const comments = post.getComments();

Q: What are the limitations of many-to-one relationships in TypeORM?

There are a few limitations to many-to-one relationships in TypeORM. For example:

  • You cannot have a self-referential many-to-one relationship.
  • You cannot have a many-to-one relationship between two entities with the same primary key type.
  • You cannot have a many-to-one relationship between two entities with a composite primary key.

Q: What are the best practices for using many-to-one relationships in TypeORM?

Here are a few best practices for using many-to-one relationships in TypeORM:

  • Use the `@JoinColumn` decorator to specify the foreign key column on the related entity.
  • Use the `@JoinTable` decorator to specify the join table for the relationship.
  • Use the `@OnDelete` decorator to specify the cascading delete strategy for the relationship.
  • Use the `@Relation()` decorator to specify the custom relation options.

    In this article, we have discussed the TypeORM many-to-one relationship. We have seen how to define a many-to-one relationship in TypeORM, how to create instances of the child entity, and how to access the parent entity from the child entity. We have also seen how to use the join table to define a many-to-one relationship.

Here are the key takeaways from this article:

  • A many-to-one relationship is a relationship between two entities where one entity can have many instances of the other entity.
  • To define a many-to-one relationship in TypeORM, you use the `@ManyToOne` decorator.
  • To create instances of the child entity, you use the `save()` method.
  • To access the parent entity from the child entity, you use the `parent()` method.
  • To use the join table to define a many-to-one relationship, you use the `@JoinTable` decorator.

I hope this article has been helpful. Please feel free to leave any questions or comments below.

Author Profile

TypeORM Many to One Relationship: A Guide for Beginners (1)

Marcus Greenwood
Hatch, established in 2011 by Marcus Greenwood, has evolved significantly over the years. Marcus, a seasoned developer, brought a rich background in developing both B2B and consumer software for a diverse range of organizations, including hedge funds and web agencies.

Originally, Hatch was designed to seamlessly merge content management with social networking. We observed that social functionalities were often an afterthought in CMS-driven websites and set out to change that. Hatch was built to be inherently social, ensuring a fully integrated experience for users.

Now, Hatch embarks on a new chapter. While our past was rooted in bridging technical gaps and fostering open-source collaboration, our present and future are focused on unraveling mysteries and answering a myriad of questions. We have expanded our horizons to cover an extensive array of topics and inquiries, delving into the unknown and the unexplored.

Latest entries
  • December 26, 2023Error FixingUser: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023How To GuidesValid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023Error FixingHow to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023TroubleshootingHow to Fix the `sed unterminated s` Command
TypeORM Many to One Relationship: A Guide for Beginners (2024)
Top Articles
Latest Posts
Article information

Author: Wyatt Volkman LLD

Last Updated:

Views: 5517

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Wyatt Volkman LLD

Birthday: 1992-02-16

Address: Suite 851 78549 Lubowitz Well, Wardside, TX 98080-8615

Phone: +67618977178100

Job: Manufacturing Director

Hobby: Running, Mountaineering, Inline skating, Writing, Baton twirling, Computer programming, Stone skipping

Introduction: My name is Wyatt Volkman LLD, I am a handsome, rich, comfortable, lively, zealous, graceful, gifted person who loves writing and wants to share my knowledge and understanding with you.