I have company and user as many to many relationship.
A company can have many users and a user can have many companies.
I have the following tables:
Company (id, name)
User (id, name)
User_Company (userId, companyId)
How do I search by company’s name and by a user?
Eg. Search company where name = "Apple" and userId = 1
Example result:
[
{
"id": 1,
"name": "Apple",
"users": [
{
"id": 1,
"name": "User 1"
},
{
"id": 5,
"name": "User 5"
}
]
},
{
"id": 3,
"name": "My Apple",
"users": [
{
"id": 1,
"name": "User 1"
},
{
"id": 2,
"name": "User 2"
}
]
}
]
Note: I’m using TypeOrm with Postgresql
2
Answers
To achieve this using TypeORM, you can define the entities for Company, User, and User_Company and their relationships as follows:
With these entities defined, you can use TypeORM’s query builder to construct a query that joins the Company, UserCompany, and User entities based on their relationships and applies filters to the result set based on the company name and user ID.
Here’s an example of how to achieve this:
This code uses TypeORM’s query builder to construct a query that joins the Company, User, and UserCompany entities based on their relationships. It then applies filters to the result set using the where method to limit the results to only those where the company name is "Apple" and the associated user has an ID of 1.
It gives :