【问题标题】:Get categories with its related post获取类别及其相关帖子
【发布时间】:2019-11-25 09:07:07
【问题描述】:

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

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

它不工作。我期待着任何建议。

【问题讨论】:

    标签: php laravel eloquent laravel-6


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-26
        • 2019-01-23
        • 2021-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多