php - Laravel Eloquent find posts that has all the given tags
问题描述
Consider 3 tables as below
class Post extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tags', 'post_id', 'tag_id');
}
}
posts
table
|id | title |
+---+---------+
|1 | post1 |
|2 | post2 |
|3 | post3 |
|4 | post4 |
tags
table
|id | value |
+---+---------+
|1 | tag01 |
|2 | tag02 |
|3 | tag03 |
|4 | tag04 |
post_tags
table
| post_id | tag_id |
+----------+---------+
| 1 | 1 |
| 2 | 3 |
| 2 | 4 |
| 3 | 1 |
| 4 | 1 |
| 4 | 4 |
The only post that has both tag01
and tag04
is post with id = 4
But when I get posts
with this code
Post::whereHas('tags', function($q) {
$q->whereIn('tag_id', [1, 4]);
}
I get all the posts that has tag01
or tag04
.
I want to get Post
s where have both tag01
and tag02
in its tags
relation.
How can I achieve this result using Eloquent
or if it's not possible using QueryBuilder
解决方案
我认为您可以使用多个 where 条件
Post::whereHas('tags', function($q) {
$q->where('tag_id', 1);
})->whereHas('tags', function($q) {
$q->where('tag_id', 4);
})->get();
如果 id 是动态的,那么
$id=[1,4];
Post::where(function($query)use($id){
foreach ($id as $value){
$query->whereHas('tags',function ($query)use($value){
$query->where('tag_id',$value);
});
}
})->get();
推荐阅读
- amazon-redshift - 将 gzip 压缩的 json 文件加载到 redshift
- ssl - openssl s_client -showcerts 未显示所有证书
- javascript - 当搜索过滤器应用于 angularjs 中的 ng-repeat 列表时,dragular 服务不起作用
- html - 计算输入值
- go - Bigquery存储grpc写api
- php - PHP MySqli 显示相似术语的结果(关键字)
- java - 拆分实例数据返回不正确的输出
- python - 如何对相同键的值求和
- javascript - MongodDB“未捕获的异常:SyntaxError:非法字符:@(shell):1:19”
- python - 为什么我的 PySpark 函数 2 给出错误而函数 1 工作正常,从逻辑上讲,它们都在做同样的事情?有人可以帮我理解吗?