通过相关帖子获取类别

时间:2019-11-25 09:07:07

标签: php laravel eloquent laravel-6

我的应用程序在两个模型之间建立了以下关系。

Post.php

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

Category.php

public function post()
{
    return $this->hasMany('App\Post', 'category_id');
}

我想以以下格式获取数据:

  1. 类别标题1

    • 帖子标题1
    • 帖子标题2
    • 帖子标题3
  2. 类别标题2

    • 帖子标题1
    • 帖子标题2
    • 帖子标题3
  3. 类别标题

    • 帖子标题1
    • 帖子标题2
    • 帖子标题3

控制器

$posts = Post::all();
$categories = $posts->pluck('category')->unique();

查看/刀片

@foreach($categories as $category)
    {{  $category->name }}
    @foreach($category as $item)
        {{  $item->post->name }}
    @endforeach
@endforeach

不起作用。我期待任何建议。

2 个答案:

答案 0 :(得分:0)

更改关系。在关系中添加外键。您不必选择类别和帖子中的其他变量。如果正确分配了关系,关系将获得所有数据。

public function category()
{
    return $this->belongsTo('App\Category', 'category_id','category_id');
}
public function post()
{
    return $this->hasMany('App\Post', 'category_id','category_id');
}
$categories = Category::all();

可见

@foreach($categories as $category)
 {{$category->name}}
 @foreach($category->post as $post)
    {{$post->title}}
 @endforeach
@endforeach

答案 1 :(得分:0)

我认为最好将manyToMany方法名(posts而不是post使用复数形式,但是在当前情况下,此代码应该可以工作:

 @foreach($categories as $category)
      {{$category->name}}
      @foreach($category->post as $item)
        {{$item->title}}
     @endforeach
  @endforeach`