【问题标题】:Longchain relationship in laravellaravel中的长链关系
【发布时间】:2018-04-03 13:01:01
【问题描述】:

我有三个模型 Post.php 是主要模型,与其他两个模型 Category.phpTags.php 相关,它们的方式如下:

 class Post extends Model
{
    public function category() 
   {
    return $this->belongsTo('App\Category', 'category_id');
   }

   public function tags()  
   {
    return $this->belongsToMany('App\Tags');
   }
}

我正在尝试获取具有相同标签名称的博客文章的所有类别名称。

这是我尝试过的:

 public function getByTag($tag)
{
    $tags = Tag::where('name','=',$tag)->first();
    $posts = $tags->posts()->get();
    foreach ($posts as $post) {
        echo($post->category->name.'<br>');
    }
}

上面的代码在某种程度上完成了这项工作(重复以前使用的类别,因为它正在打印每个帖子的类别)。而且我只想打印一次所有相关的类别名称。

如果有人能建议我正在寻找的输出的最佳查询方法,我将非常感激?

更新 添加表结构

    posts
   id - integer
   title - string
   content - text
   category_id -integer
category
   id - integer
   name - string
tags
   id - integer
   name - string
posts_tags
   id - integer
   post_id - integer
   tag_id -integer

【问题讨论】:

标签: php laravel laravel-5.5


【解决方案1】:

试试这个:

$tags = Tag::where('name','=',$tag)->first();
$posts = $tags->posts()->with('category')->get(['category_id']);
$categories = $posts->pluck('category')->unique();

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    相关资源
    最近更新 更多