Reputation: 7416
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):
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
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