Kai021195
Kai021195

Reputation: 833

How to query an one to one to many relationship using TypeORM query builder?

So right now I have four tables

**Users**
user_id;
**Categories**

category_id;
user_id;
**Todos**

todo_id;

**Categories_Todos** (joinTable)

category_id;

todo_id;

so there relationship are

1. A user can have a lot of categories ( one to many)
2. Categories can have a lot of Todos and Todos can also have a lot Categories(many to many)

I accomplish get's certain categories's todo's by following query buillder

const response = await getRepository(TodoItem)
      .createQueryBuilder("todoItem")
      .leftJoin('todoItem.categories', 'categories')
      .where('categories.id=:id',{id:categoryId})
      .getMany();

But what I really want to do is to get a user's todos by userID, I think it's like an one to many to many relationship , how can I do that ?

Upvotes: 0

Views: 5543

Answers (1)

hp10
hp10

Reputation: 632

You should also join user table and then get all distinct values:

const response = await getRepository(TodoItem)
  .createQueryBuilder("todoItem")
  .leftJoin('todoItem.categories', 'categories')
  .leftJoin('categories.user', 'user')
  .where('user.id=:id',{id: userId})
  .distinct(true)
  .getMany();

Upvotes: 1

Related Questions