【发布时间】:2018-06-25 04:17:27
【问题描述】:
该设置由两个表(线程、标签)和一个数据透视表(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);
你能想出更好的解决方案吗?谢谢!
【问题讨论】:
-
JOIN tags AS ta ... JOIN tags AS tb ...
标签: mysql laravel eloquent many-to-many pivot-table