Many to Many query on Lucid models, AdonisJs

1.1k views Asked by At

Consider a simple situation of users and subjects related with a pivot table named user_subjects, now if I have to fetch all the users who have opted for a certain subject. What is the best way to achieve this in AdonisJs 5. Following is the solution I found.

const subject = await Subject.find(req.params.id);


const users = await subject.related('users').query();

There is nothing wrong with the above approach but I think there is an extra query to fetch the entity and then load the relationship. Is there a more optimised way to achieve above?

Also to take the above example a bit further, if suppose users are related to classes through a pivot table user_classes, can that not be achieved using 1 query on Lucid Models and not using Database class?

0

There are 0 answers