I didn't test it, but how about something like this?
$tags = explode(',', Input::get('tags'));
foreach ($tags as $tag) {
$tag = str_replace('-', ' ', $tag);
$list = $list->whereHas('tags', function ($query) use ($tag) {
$query->whereTag($tag);
});
}
Thanks, that seems to be what I'm looking for. The only thing that troubles me is that this method generates a sub query for each of the tags, but I suppose there's no way around that.
If you'd like to avoid subqueries, you can use a query like that:
SELECT `characters`.*, COUNT(`tags`.`id`) AS `tags_matches_count`
FROM `character_tag`
JOIN `characters`
ON `characters`.`id` = `character_tag`.`character_id`
JOIN `tags`
ON `tags`.`id` = `character_tag`.`tag_id`
WHERE `tags`.`tag` IN ('dogs', 'puppies')
GROUP BY `characters`.`id`
HAVING `tags_matches_count` = 2
You would need to pass a list of tags there (in place of dogs and puppies) and their number (in place of 2). I believe that would be more efficient.
I'd rather keep the Laravel syntax, it looks way nicer (besides, I don't think the performance gain would be anything to really bother with). If there are problems, I'll most likely just cache the entire model later on and build a paginator manually, as that seems to be the most efficient method.
Thanks a lot for contributing
I always try to avoid raw queries too :) Plus, subqueries are a lot better than new queries.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community