php - 在数据透视表中我存储了 post_id 和 category_id 如何从数据透视表中获取我的帖子类别名称?
问题描述
这是我的类别模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}
这是我的帖子模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
public function user()
{
return $this->belongsTo('App\User');
}
}
这是我的索引功能
public function index()
{
$posts=Post::latest()->get();
return view('admin.post.index',compact('posts'));
}
这是我的查看页面
@foreach($posts as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ str_limit($post->title,'10') }}</td>
<td>{{$post->categories->pivot->name}}</td>
</tr>
@endforeach
当我想回显我的类别名称时,laravel 给了我这个错误。
此集合实例上不存在 ErrorException (E_ERROR) 属性 [pivot]。(查看:C:\xampp\htdocs\Advanced_Blog_System\resources\views\admin\post\index.blade.php)
我只需要查看类别名称我该如何解决这个问题???
解决方案
Post 和 Category 都具有多对多的关系,因此您需要另一个 foreach 类别;
@foreach($post->categories as $category)
{{$category->name}}
@endforeach
推荐阅读
- html - 在反应中的 SVG 文件上找不到模块
- python-3.x - 拆分后如何用逗号连接字符串:Python
- ms-access - 如何使用单击事件上的删除按钮从数据表中删除记录(通过鼠标选择)?
- javascript - 在工作表中,当单元格被填满时向特定收件人发送电子邮件
- arrays - io::Read 在新类型上的特征实现
- r - R / lubridate:计算两个时期之间的重叠天数
- angular - 如何在基于 Angular 6 的给定 JHipster webapp 中使用 angular-file-md5 计算文件的哈希?
- sharepoint-online - 如何检查按钮公式中组合框(所选项目)的值(可见属性)
- python - 如何在 Google Cloud Shell 上安装库 python-docx / docx?
- arrays - window.enableMouseFlow 在 componentDidMount() 中未定义,但在 render() 中可用