I am trying to implement a way to filter data in tables which have ManytoMany relationship.
I have following tables job, job_category and category.
So far I am thinking in do a query to job_category using job_id and then use that result to add a condition using IN() but I do not find any way to impĺement this option either.
Questions:
How to implement ManytoMany relation in Loopback 4?
How to filter a query using IN?
PD I can use $inq for question number 2.
filter.where = {
...filter.where,
id: {inq: [2, 7]},
};
Taking the context of your question, a many-to-many relationship can be implemented in lb4 as below.
The jobs model (a sample) -
The categories model (a sample) -
In the Job categories relationship model, we are going to implement the belongs to relationship with both Job and Category Models. This will ensure m:n relationship.
Now, using lb4 CLI, you can create a repository and REST controller for job categories model and use the find methods there to fetch data. Unfortunately, includes parameter in Filter class for find methods is not yet implemented in lb4. Its still WIP. Refer this thread from loopback-next repo for updates. Until then, you may have to add custom logic t controller or repository classes to achieve this. Two suggested approaches from my side are below.
Hope this helps with your question #1. For question #2, you already mentioned the approach. That works.
You can implement a many-to-many relationship in Loopback 4 using the hasManyThrough relationship. The hasManyThrough relationship is an extension to the hasMany relationship.
Currently, this feature is a pull request waiting to be accepted.
https://github.com/strongloop/loopback-next/pull/2359
However, the code for this pull request has been packaged and can be installed and used the following way.
models/patient.model.ts
repositories/patient.repository.ts
There is a basic example of this at the following link.
https://github.com/codejamninja/medical-practice-api
Please note that this api may change before the pull request is accepted.
You can read more about how this relationship works at the following links.
https://loopback.io/doc/en/lb3/HasManyThrough-relations.html https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association