首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何统计外键重复的项?

如何统计外键重复的项?
EN

Stack Overflow用户
提问于 2019-06-04 21:59:44
回答 1查看 582关注 0票数 0

如何计算具有相同外键的项,同时仍然可以访问关系数据?

我使用的是PHP - Laravel - Eloquent,有三个表:UserUser_itemsitems

User_items有三列:iduser_iditem_id

ID | user_id | item_id
0  | 5       | 2  
1  | 5       | 3  
2  | 5       | 8  
3  | 5       | 3  

假设items也有三列:idnamevalue

ID | Name    | Value
2  | Sword   | 500  
3  | Pickaxe | 250  
8  | Shovel  | 700  

我想对具有相同user_id的条目进行计数,并从items表返回条目数据。为了获取所有用户项,我使用以下关系:

    public function user_items()
    {
        return $this->hasMany(User_items::class, 'user_id', 'id');
    }

接下来,我想获取这些项目的名称并对其进行计数。我不只是想:

Sword
Pickaxe
Shovel
Pickaxe

不知何故,我希望得到这样的结果:

2 Pickaxe
1 Sword
1 Shovel

我的user_items关系,用来获取一个项目的数据如下所示:

    public function item_data()
    {
        return $this->hasOne(Items::class, 'id', 'item_id');
    }

这就是我如何得到可重复的结果:

return response()->json(["DATA" => $user->user_items->load('item_data')->toArray()], 201);

输出示例

   "DATA":[  
      {  
         "id":1,
         "item_id":5,
         "created_at":"2019-06-04 08:44:08",
         "updated_at":"2019-06-04 08:44:08",
         "item_data":{  
            "id":5,
            "name":"Sword",
            "rarity":"good",
            "value":500,
            "image":"image.jpg",
            "color":"#3160ed",
            "created_at":null,
            "updated_at":null
         }
      },
}

我想在上面的输出中添加像"count": 5这样的行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-05 08:37:29

我认为你需要的是一个用户和一个项目之间的多对多关系。

为了更好的命名约定,我将表重命名为: users、user_item、items。

class User
{
    public function items()
    {
        return $this->belongsToMany(Item::class)
    }
}

为每个用户返回项目和每个项目的数量。你可能会这样做。

$items = $user->items()->select('items.*', 'count(items.id) AS items_count')
    ->groupBy('items.id')
    ->get()
    ->toArray();

// From the controller, this array will be automatically converted to json.
return ['DATA' => $items];

你会得到类似这样的东西。不完全是您想要的格式,但我认为最好保持这种格式。

[
    'DATA' => [
        {
            "id":5,
            "name":"Sword",
            "rarity":"good",
            "value":500,
            "image":"image.jpg",
            "color":"#3160ed",
            "created_at":null,
            "updated_at":null,
            items_count: 1
        }
    ]
]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56445497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档