TypeORM: search in relationships (ft. NestJS)
Because I didn’t want to perform a full search once I brought all the records. Since SQL is really optimized for queries. For this case, I wanted to filter some records based on their relationship attributes.
I’ll use a simple test case.
💡 First, we need two TypeORM entities
For the most simple of cases, let’s suppose we have two classes. A
Pet and an
Owner. A Pet will belong to only one Owner. Both entities live in the same folder.
🔨 Creating the method for the controller
We will use NestJS. A simple NestJS controller seems like the following example.
As you see here. The URL for the search will be
🚛 Using Repositories
This is the method Typescript friendly. I prefer this since I’ll have type validation if I update any field in the future.
It will produce the following query
🚛 Using Query Builder from repositories
This method is more close to SQL. Useful if you’re more comfortable with it.
The query for the function above will result as
⭐ Final result
This is the final controller. I’ll add a docker-compose file if you want to try it by yourself. Also, there is a
/fake method to create records if you want to test the search.
Remember, this is ONLY the main controller. Check my FULL demo on Github here