我想列出所有的帖子至少有一个标签在我所选择的每一个类别。在我们的laravel应用程序中,我们有一个邮政和标签模型。
在Post模型中,我们有:
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tags', 'post_id', 'tag_id');
}什么是查询以选择post至少有一个{3,2}标签和至少一个{8,10}?
我写这段代码:
$tags = ['news' => [3,2], 'alert' => [8,10]];
Post::whereHas('tags', function($query) use ($tags){
foreach($tags as $category => $tag){
$query->whereIn('tags.id', $tag);
}
}帖子
+---------+---------------+
| id | title |
+---------+---------------+
| 1 | post 1... |
| 2 | post 2... |
| 3 | post 3... |
| 4 | post 4... |
| 5 | post 5... |
| 6 | post 6... |
| 7 | post 7... |
| 8 | post 8... |
| 9 | post 9... |
+---------+---------------+标签
+---------+-------+------------+
| id | name | category |
+---------+-------+------------+
| 1 | stock | news |
| 2 | acc | news |
| 3 | etc | news |
| 4 | eco | news |
| 5 | side | ads |
| 6 | head | ads |
| 7 | footer| ads |
| 8 | info | alert |
| 9 | danger| alert |
| 10 |success| alert |
+---------+-------+------------+post_tags
+-----------+---------+
| post_is | tag_id |
+-----------+---------+
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 1 | 8 |
| 1 | 9 |
| 1 | 10 |
| 9 | 9 |
| 9 | 6 |
| 3 | 7 |
| 7 | 1 |
| 7 | 2 |
| 7 | 8 |
+-----------+---------+但结果不算什么。
我需要结果,因为后雄辩和查询的性能是重要的。
larave版本为5.8.35
发布于 2019-10-31 06:25:55
我从一个原始的MySQL查询开始,它完成了工作。然后,围绕这一点建立你的Laravel脚本。
SELECT
p.id,
p.title
FROM posts p
INNER JOIN post_tags pt
ON pt.post_id = p.id
GROUP BY
p.id,
p.title
HAVING
SUM(pt.tag_id IN (2, 3)) > 0 AND
SUM(pt.tag_id IN (8, 10)) > 0;你的Laravel密码:
$posts = DB::table('posts p')
->join('post_tags pt', 'pt.post_id', '=', 'p.id')
->groupBy('p.id', 'p.name')
->havingRaw('SUM(pt.tag_id IN (2, 3)) > 0 AND SUM(pt.tag_id IN (8, 10)) > 0')
->select('p.id', 'p.name')
->get();https://stackoverflow.com/questions/58637768
复制相似问题