0

I'm using TypeORM query builder for my backend and I have an issue i will appreciate your help with. I have three data base tables - USERS, ITEMS & USER_FAVORITES_ITEMS (relation table). each USER have MANY favorites items and each item can be FAVORITE to many USERS (Many To Many relation).

Now, the result I'm looking for is to create query that will return all items on the database with extra column called IS_FAV (boolean) -> if the item appears in the USER_FAVORITES_ITEMS for this user I want it to be TRUE, else it should be FALSE.

enter image description here

This is how my MANY To Many table looks like (very simple).

1
  • Can you pls. show the expected structure of the result set? And users is the same as tourists, right? Commented Jun 29, 2021 at 13:06

2 Answers 2

0

you should use this:

 let query = this.userRepository
      .createQueryBuilder('ITEMS')
      .leftJoin('ITEMS.USERS', 'USERS')
      .select('ITEMS')
      .addSelect('ITEMS.USERS)', 'USER_FAVORITES_ITEMS');
    const inputs = await query.getRawMany();
inputs.map((item)=>{
if(item.USERS){
return {
...item,
USER_FAVORITES_ITEMS: true,
}
} else {
return {
...item,
USER_FAVORITES_ITEMS: true,
}
}
});

you may change the code to what you want, but you can use this way.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank a lot. I was able to achieve the required result using the 'getRawMany' - BUT I wonder if there is a good way to keep the entity structure (which means not using getRawMany OR something else I didn't think about). any idea ?
i searched for some feature like this, but i was unable, only raw many work, structure is a bit disrupt, if yoy log the result can find how to extract data. let me write a piece of code about how to extract data
0

this is how to derive values from getRawMany():

export default class **** {
  constructor(data: any) {
    const product: Product = {
      createdById: data.product_createdById,
      updatedById: data.product_updatedById,
      productCategory: {
        createdById: data.category_createdById,
        updatedById: data.category_updatedById,
      },
    };
  ********
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.