【问题标题】:How to show the category name for each articles?如何显示每篇文章的类别名称?
【发布时间】: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


【解决方案1】:

在图像模型中

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
   }
}

【讨论】:

  • 方法 Illuminate\Database\Query\Builder::all 不存在。
  • 换成get(),赚了
  • @DivMan Ops,抱歉我忘记更改了,应该是 get(),我更新了我的问题
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多