Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

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);
    });
}
Last updated 9 years ago.
0

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.

0

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.

0

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

0

I always try to avoid raw queries too :) Plus, subqueries are a lot better than new queries.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.