简体   繁体   English

Laravel获得带有多个标签的帖子

[英]Laravel get posts with multiple tags

I'm working with a laravel belongsToMany relationship between Post and Tag . 我正在与laravel PostTag之间的Laravel belongsToMany关系合作。

What I'm trying to do is get all Post s where it has multiple tags. 我想做的是将所有Post包含多个标签。

I've tried all sorts of eloquent queries, but I can't get it at all. 我已经尝试过各种雄辩的查询,但是我根本无法理解。

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. 目前,我可以得到一个post_idtag_id的数组,如下所示,但是必须有一种更简单的方法来做到这一点。

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());

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. 这将转储具有任何ID的所有帖子的数组,但是我需要获得一个post_id数组,其中包含所有tag_id

Thanks in advance! 提前致谢!

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. 最好在Post模型上使用whereHas()来渴望加载标签,并仅获取具有至少一个标签的Post

$posts = Post::whereHas('tags', function($q) use ($tags)
{
    $q->whereIn('id', $tags);
})->get();

Here, $tags would just be an array of tag id's. 在这里, $tags只是一个标签ID的数组。 $posts would be a Collection of Post s. $posts将是PostCollection To get the array of id's from it, you can simply do this... 要从中获取ID数组,您可以简单地执行此操作...

$ids = $posts->lists('id'); 

Or instead of calling get() originally, use ...->lists('id') 或代替最初调用get() ,而使用...->lists('id')

Edit 编辑

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. 如果仅查找包含所有标记的PostwhereHas将一些其他参数传递给whereHas函数。

$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. 如果您使用这种方法,请确保正确管理数据透视表,因为不能将某个标签多次附加到某个模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM