Laravel 查询多对多关系
我有一个 API 来跟踪照片和标签。每张照片可以有 N 个标签,一个标签可以链接到 N 张照片。这是使用 3 个表完成的:
- 照片表。
- 标签的表。
- photo_tag关系表。
现在,我正在努力让所有照片都标记有一组标签,其想法是使用标签列表向我的 API 发出请求,并获取至少包含所有标签的照片列表。
我一直在尝试使用 whereIn
运算符。
这是我的代码(现在全部是硬编码的):
$photos = Photo::whereHas('tags', function (Builder $query) {
$query->whereIn('tag', ['a5', 'mate', 'Brillante']);
})->get();
return response()->json($photos, 200);
当我执行它时,它会返回与一个标签匹配的所有照片,而我只需要具有所有请求标签的照片(在本例中为 a5,mate)。
我正在开发 Laravel 9。
编辑:
正如 Tim Lewis 建议的那样,我尝试过循环:
$tags = array("a5", "mate", "Brilante");
$photoQuery = Photo::query();
foreach($tags as $tag) {
\Log::debug($tag);
$photoQuery->whereHas('tags', function($query) use ($tag) {
return $query->where('tag', $tag);
});
}
$photos = $photoQuery->get();
现在它返回一个空列表,我认为是因为正在寻找仅具有我在数组上硬编码的 3 个标签的照片。
编辑2:
看来这些更改是正确的,但由于某种原因,邮递员没有向我显示这些更改的任何结果是我的问题的解决方案。
I have an API to keep tracked photos and tags. Each photo can have N tags and one tag can be linked to N photos. That's done using 3 tables:
- Photo's table.
- Tag's table.
- photo_tag relation table.
Now I'm working to get all photos tagged with a set of tags the idea is to make requests to my API with a list of tags and get a list of photos that has at least all the tags.
I've been trying with the whereIn
operator.
This is my code (now it's all hardcoded):
$photos = Photo::whereHas('tags', function (Builder $query) {
$query->whereIn('tag', ['a5', 'mate', 'Brillante']);
})->get();
return response()->json($photos, 200);
When I execute it it return all that photos that match one tag and I need only photos that hast all the requested tags (in this example a5, mate).
I'm working on Laravel 9.
Edit:
As Tim Lewis suggested I've tried looping:
$tags = array("a5", "mate", "Brilante");
$photoQuery = Photo::query();
foreach($tags as $tag) {
\Log::debug($tag);
$photoQuery->whereHas('tags', function($query) use ($tag) {
return $query->where('tag', $tag);
});
}
$photos = $photoQuery->get();
Now it's returning an empty list I think because is looking for Photos that only have the 3 tags I hardcoded on the array.
Edit 2:
It seems that those changes were right, but for some reason Postman was not showing me any results of those changes are the solutions to my issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
whereIn()
方法与所提供的任何个值匹配,而不是全部,因此您需要对此进行修改。指定多个whereHas()
子句(每个标签 1 个)应该有效:现在,取决于发送到 API 的
tags
(假设通过$ request
变量作为'tags' => []
数组),此查询将为每个 Tag 包含一个whereHas()
子句,并且仅返回 < code>Photo 已指定所有记录标签。Since the
whereIn()
method matches against any of the values provided, and not all, you'll need to modify this. Specificying a number ofwhereHas()
clauses, 1 for each Tag, should work:Now, depending on the
tags
being sent to your API (assuming through the$request
variable as a'tags' => []
array), this query will include awhereHas()
clause for each Tag, and only returnPhoto
records that have all specified Tags.