Laravel:如何在数据透视表的显示视图中显示CategoryTitle

问题描述

我想在帖子视图中显示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]。

解决方法

您无法直接访问它,使用belongsToMany您将获得多个对象。

要访问此文件,您需要按照以下说明进行操作。

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...