【问题标题】:Laravel : how to show CategoryTitle in show views from pivot tableLaravel:如何在数据透视表的显示视图中显示类别标题
【发布时间】:2020-08-18 12:42:59
【问题描述】:

我想在帖子视图中显示 category_title。我正在为 category_id 和 post_id 使用数据透视

帖子模型:

public function categories()
{
        return $this->belongsToMany(Category::class,'category_post','post_id','category_id');
}

Show.blade.php

{{$post->categories->category_title}}

但是告诉我这个错误

此集合实例上不存在属性 [category_title]。

【问题讨论】:

    标签: laravel relation


    【解决方案1】:

    你不能直接访问它,belongsToMany 你会得到多个对象。

    要访问它,您需要按照以下方式进行操作。

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

    或者您可以按以下方式访问它。

    {{ $post->categories->pluck('category_title ')->implode(',') }}
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 2021-07-18
      • 1970-01-01
      • 2013-04-07
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多