【发布时间】:2022-01-12 15:46:23
【问题描述】:
我目前正在使用 group by 检索数据,以获得相同的宝藏名称、找到的总数和相同的宝藏数量(上限)。使用下面的代码,我可以得到所有的宝物数据,但是当宝物被完全认领时,它无法显示total_left为0。
*claimed 列是一个布尔值,其中 0 尚未被声明。 *cap 是同一地点的总宝藏
查询
$treasure_hunt_data = TreasureHunt::where('claimed', '0')
->selectRaw(" treasure_name, count(claimed) as total_left, cap")
->groupBy(['treasure_name', 'cap'])
->get();
数据
[
{"treasure_name":"Location A","total_left":5,"cap":5},
{"treasure_name":"Location B","total_left":2,"cap":2},
{"treasure_name":"Location C","total_left":2,"cap":2},
{"treasure_name":"Location D","total_left":10,"cap":10}
]
所需数据
[
{"treasure_name":"Location A","total_left":5,"cap":5},
{"treasure_name":"Location B","total_left":2,"cap":2},
{"treasure_name":"Location C","total_left":2,"cap":2},
{"treasure_name":"Location D","total_left":10,"cap":10},
{"treasure_name":"Location E","total_left":0,"cap":1}
]
数据库数据
迁移详情
Schema::create('treasure_hunts', function (Blueprint $table) {
$table->id();
$table->string('treasure_name');
$table->boolean('claimed')->default(0);
$table->string('cap');
$table->timestamps();
});
【问题讨论】:
-
请添加模型和迁移详细信息以及所需输出的示例数据,以便我们了解您的数据库是什么样的。
-
@miken32,我已经添加了迁移细节和数据库数据
-
请勿发布代码图片
标签: php laravel eloquent laravel-8