soren.qvist
soren.qvist

Reputation: 7416

Find suggestions based on interests using Laravel and Eloquent

I'm building a small site where users can receive movie recommendations based on their preferences for some attributes, such as genre, year or running time. My database looks like the following (the arrows signifies many-to-many relationships):

enter image description here

Assuming I have a model for each entity in the picture, how do I find which movies I should recommend to a user?

Upvotes: 0

Views: 1980

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153070

What you are looking for can be accomplished by using whereHas:

Movies::whereHas('genres.users', function($q) use ($userId){
   $q->where('users.id', $userId);
})->whereHas('years.users', function($q) use ($userId){
   $q->where('users.id', $userId);
})->whereHas('runtimes.users', function($q) use ($userId){
   $q->where('users.id', $userId);
})->get();

This basically filters movies by the nested relationship users (over the three other relations)

Upvotes: 2

Related Questions