【发布时间】:2019-02-09 09:33:36
【问题描述】:
我使用多对多关系。
需要列出帖子所属类别的文章,我在构建器的帮助下完成了此操作,因为我不知道如何通过 ORM 执行此操作。
我有三张桌子:
类别 -ID -名称
图片 -ID -图片 -描述
category_image(数据透视表) -ID -image_id -category_id
public function getCategoryTitle($id)
{
$post = DB::table('category_image')
->where('image_id', '=', $id)
->get();
$categoryImage = $post->toArray()[0]->category_id;
$showCategory = DB::table('categories')
->where('id', '=', $categoryImage)
->get();
return $showCategory->toArray()[0]->name;
}
现在事实证明,对于每篇文章,对数据库的请求都会多出 2 个,这非常糟糕。
输出所以
public function index()
{
$posts = Image::all();
return view('admin.posts.index', ['posts'=>$posts]);
}
我尝试使用 ->
获取类别名称@foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->description}}</td>
<td>{{$post->getCategoryTitle($post->id)}}</td>
<tr>
@endforeach
图像模型
dd( $this->belongsToMany(
Category::class,
'category_image',
'image_id',
'category_id',
1
));
是否有任何简单的方法可以使用关系获取每个图像的类别名称。
【问题讨论】:
-
你想为每张图片显示类别名称吗?
标签: laravel