Php 获取类别及其相关帖子

Php 获取类别及其相关帖子,php,laravel,eloquent,laravel-6,Php,Laravel,Eloquent,Laravel 6,我在我的应用程序中建立了以下两个模型之间的关系 Post.php 公共功能类别() { 返回$this->belongsTo('App\Category','Category_id')->withDefault(); } Category.php public function post() { 返回$this->hasMany('App\Post','category_id'); } 我希望在视图中以以下格式获取数据: 类别标题1 职位名称1 职位名称2 职位名称3 类别标题2 职位

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

Post.php

公共功能类别()
{
返回$this->belongsTo('App\Category','Category_id')->withDefault();
}
Category.php

public function post()
{
返回$this->hasMany('App\Post','category_id');
}
我希望在视图中以以下格式获取数据:

  • 类别标题1

    • 职位名称1
    • 职位名称2
    • 职位名称3
  • 类别标题2

    • 职位名称1
    • 职位名称2
    • 职位名称3
  • 类别名称

    • 职位名称1
    • 职位名称2
    • 职位名称3
  • 控制器

    $posts = Post::all();
    $categories = $posts->pluck('category')->unique();
    
    视图/刀片

    @foreach($categories作为$category)
    {{$category->name}
    @foreach($类别为$项目)
    {{$item->post->name}
    @endforeach
    @endforeach
    

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

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

    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
    

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

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