【问题标题】:Get the quantity and name of an object between related tables获取相关表之间对象的数量和名称
【发布时间】:2020-04-27 19:33:08
【问题描述】:

我正在从我的 Animals 表中获取数据,该表与 Categories 表有关系。我的问题是我需要计算每个类别注册了多少产品。

在 Stackoverflow 上进行搜索时,我开始使用下面的代码返回每个类别的动物数量([Animal,数量])。

$data = DB::table('animals')
                ->select(
                    DB::raw('category_id as category'),
                    DB::raw('count(*) as number'))
                ->groupBy('category')
                ->get();
            $array[] = ['Name', 'Quantity'];
            foreach($data as $key => $value)
            {

                $array[++$key] = [$value->category, $value->number];
            }
            $cat = json_encode($array);
            dd($cat);

使用“dd”,我看到下面的数据是正确的,但是category_id来了,我不知道如何获取这个id并为那个id放置类别名称。

"[["Category","Quantity"],[1,10],[2,14],[3,30],[4,26],[5,1]]"

示例:[2,14] 这指的是 category_id 2,其名称为:ma​​mmal。所以我会在哺乳动物类别中注册 14 种动物。

我希望结果是这样的:

"[["Category","Quantity"],[birds,10],[mammals,14],[reptiles,30],[amphibians ,26],[fish,1]]"

如何处理这个与类别名称相关的 id?

【问题讨论】:

  • DB::raw('category_name as category')?
  • @u_mulder,没有。 Animals 表,有一个名为 category_id 的字段,用于存储 Category 表的外键
  • 然后你需要加入类别表并从那里获取名称。

标签: php laravel relationship


【解决方案1】:

加入您的类别表并从那里获取名称,我想它应该如下所示:

$data = DB::table('animals')
    ->join('category', 'animals.category_id', '=', 'category.id')
    ->select(
        DB::raw('category.id as category_id'),
        DB::raw('category.name as category_name'),
        DB::raw('count(*) as number'))
    ->groupBy('category')
    ->get();

More about joins

【讨论】:

    【解决方案2】:

    您可以使用模型中的“withCount”方法,它可以帮助您计算关系中结果的数量

    $posts = App\Post::withCount('comments')->get();
    foreach ($posts as $post) {
        echo $post->comments_count;
    }
    

    查看文档https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多