Laravel获得带有多个标签的帖子 [英] Laravel get posts with multiple tags
问题描述
我正在处理Post
和Tag
之间的laravel belongsToMany
关系.
I'm working with a laravel belongsToMany
relationship between Post
and Tag
.
我想做的是将具有多个标签的所有Post
都获取.
What I'm trying to do is get all Post
s where it has multiple tags.
我尝试了各种雄辩的查询,但我根本无法理解.
I've tried all sorts of eloquent queries, but I can't get it at all.
目前,我可以得到一个post_id
和tag_id
的数组,如下所示,但是必须有一种更简单的方法来实现此目的.
Currently I can get an array of post_id
's and tag_id
's, as shown below, but there has to be an easier way to do this.
if (Request::has('tags')) {
$tags = Tag::find(explode(',', Request::get('tags')));
}else{
$tags = null;
}
// Get all posts tagged with the tags
$jobs = \DB::table('post_tag');
foreach ($tags as $tag) {
$posts = $posts->orwhere('tag_id', $tag->id);
}
dd($posts->get());
这会转储具有ID的所有帖子的数组,但我需要获取一个包含所有tag_id
的post_id
数组.
This dumps an array of all posts that have any of the ID's, but I need to get an array of post_id
s where it contains all tag_id
s.
提前谢谢!
推荐答案
最好在Post
模型上使用whereHas()
来急于加载标签并仅获取具有以下内容的Post
这些标签中的至少一个.
It would be a good idea to use whereHas()
on the Post
model to eager load the tags and get only the Post
s which have at least one of those tags.
$posts = Post::whereHas('tags', function($q) use ($tags)
{
$q->whereIn('id', $tags);
})->get();
在这里,$tags
只是一个标签ID的数组. $posts
将是Post
的Collection
.要从中获取ID的数组,您可以简单地执行此操作...
Here, $tags
would just be an array of tag id's. $posts
would be a Collection
of Post
s. To get the array of id's from it, you can simply do this...
$ids = $posts->lists('id');
或者使用...->lists('id')
编辑
如果仅查找包含所有标记的Post
,则要将一些其他参数传递给whereHas
函数.
If you are looking for only those Post
s which contain all of the tags, you want to pass some additional parameters to the whereHas
function.
$posts = Post::whereHas('tags', function($q) use ($tags)
{
$q->whereIn('id', $tags);
}, '=', count($tags))->get();
将发生的情况是,它将仅抓取附加了与标签数组中的标签数量相等的标签数量的帖子.
What will happen is it will only grab posts that have a number of tags attached equal to the count of the tags in the tags array.
如果您使用这种方法,请确保正确地管理数据透视表,因为不能将某个标签多次附加到某个模型上.
If you use this approach, be sure your pivot table is managed correctly in that it is not possible to attach a certain tag to a certain model more than once.
这篇关于Laravel获得带有多个标签的帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!