Laravel获得带有多个标签的帖子 [英] Laravel get posts with multiple tags

查看:119
本文介绍了Laravel获得带有多个标签的帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理PostTag之间的laravel belongsToMany关系.

I'm working with a laravel belongsToMany relationship between Post and Tag.

我想做的是将具有多个标签的所有Post都获取.

What I'm trying to do is get all Posts where it has multiple tags.

我尝试了各种雄辩的查询,但我根本无法理解.

I've tried all sorts of eloquent queries, but I can't get it at all.

目前,我可以得到一个post_idtag_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_idpost_id数组.

This dumps an array of all posts that have any of the ID's, but I need to get an array of post_ids where it contains all tag_ids.

提前谢谢!

推荐答案

最好在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 Posts which have at least one of those tags.

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

在这里,$tags只是一个标签ID的数组. $posts将是PostCollection.要从中获取ID的数组,您可以简单地执行此操作...

Here, $tags would just be an array of tag id's. $posts would be a Collection of Posts. 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 Posts 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆