高效的MySQL / Eloquent查询,用于过滤超过1个标签的帖子

时间:2018-01-16 12:40:48

标签: mysql laravel eloquent many-to-many pivot-table

设置包括两个表(线程,标签)和一个数据透视表(tag_thread),以允许多对多关系:一个线程可以有多个标签,一个标签可以用于许多线程。

表的属性:

treads: id, title

tags: id, name

threads: id, thread_id, tag_id

现在我想使用不是一个而是多个标签来过滤线程。所以我想获得与所有给定标签相关联的所有线程?只使用一个我可以通过Laravel Eloquent使用以下模型轻松完成:

$filteredThreads = $tag->threads()->get()

我已经设法用两个标签来做,但我觉得这是一种非常肮脏且无效的方法(特别是考虑到它通过整个id列表进行比较):

$threadIds = Thread::select('th.id')
        ->from('threads AS th')
        ->join('tag_thread AS tt', 'tt.thread_id', 'th.id')
        ->join('tags AS ta', 'tt.tag_id', 'ta.id')
        ->where('ta.name', $tag)
        ->pluck('id')
        ->toArray();

return $filteredThreads->whereIn('threads.id', $threadIds);

您能想到更好的解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:3)

如果要获取具有$tagsNames数组中定义的名称之一的标记的线程:

$tagsNames = ['popular', 'cool'];
Thread::whereHas('tags', function($q) use($tagsNames) {
    $q->whereIn('name', $tagsNames);
})->get();
相关问题