如何显示每篇文章的类别名称?

问题描述 投票:1回答:2

我使用多对多关系。

有必要列出帖子所属类别的文章,我是在构建器的帮助下完成的,因为我不知道如何通过ORM来做到这一点。

我有三张桌子:

categories -id -name

图像-id -image -description

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
2个回答
4
投票

在图像模型中

public function categories(){
 return $this->belongsToMany(Category::class)
}

在类别模型中

public function images(){
 return $this->belongsToMany(Image::class)
}

with()用于预先加载,可让您在单个查询中获取类别

$posts = Image::with("categories")->get();

foreach($posts as $post) {
  foreach ($post->categories as $category){
     $category->name
   }
}

1
投票

如果你的关系用laravel正确设置,你可以使用简写 - > with('categories')(名称取决于你所属的许多函数的名称)来获取类别行

© www.soinside.com 2019 - 2024. All rights reserved.