anyone?
Jan 30, 2015
9
Level 6
Can I improve this Query? (USER, Album, Pictures, TAGS)
Hi.
I have users who has many albums, albums has many pictures and pictures has many tags.
I want to get those users who have pictures with some tags given. This is my current query:
$tags_ids = [1, 2, 3];
$filter = function($pictures) use($tags_ids) {
$pictures->with('tags');
// I'm doing this because I want to get those pictures which have ALL tags given (tags with ID 1, 2 and 3 in this case)
foreach ($tags_ids as $tag_id) {
$pictures->whereHas('tags', function($tags) use($tag_id) {
$tags->where('tag_id', $tag_id);
});
}
};
return User::with(['albums', 'albums.pictures' => $filter]) // get those users which have pictures with the given tags
->whereHas('albums', function($albums) use($tags_ids, $filter) {
$albums->whereHas('pictures', $filter); // load the pictures with the given tags
});
It works well but it seems I'm repeating code.
Level 6
@JarekTkaczyk thx, finally this is my code:
$tags_ids = [1, 10];
$filter = function($pictures) use($tags_ids) {
$pictures->whereHas('tags', function($tags) use($tags_ids) {
$tags->whereIn('tags.id', $tags_ids)->selectRaw('count(distinct tags.id)');
}, '>=', count($tags_ids));
};
$users= User::with(['pictures' => $filter])
->whereHas('pictures', $filter)
->get();
Please or to participate in this conversation.