【发布时间】:2021-06-15 20:37:57
【问题描述】:
我有 2 张名为 Resort 和 booking 的桌子。在预订表中,有一个名为金额的字段。我想使用 hasMany 关系加入这些表,并使用 groupBy 获取预订表中金额字段的总和。你能帮我解决这个问题吗?
提前致谢
【问题讨论】:
标签: php laravel group-by has-many
我有 2 张名为 Resort 和 booking 的桌子。在预订表中,有一个名为金额的字段。我想使用 hasMany 关系加入这些表,并使用 groupBy 获取预订表中金额字段的总和。你能帮我解决这个问题吗?
提前致谢
【问题讨论】:
标签: php laravel group-by has-many
Laravel Eloquent 有自己的 withSum() 方法来避免“groupBy()”方法。
对于您的情况,您可以使用这样的东西(您可以根据需要进行修改):
// resorts with bookings and their summary prices
$data = Resort::select([
'id',
'name',
'image',
])
// ->orderBy('some_field', 'ASC')
->with(['bookings' => function($query) {
return $query->select([
'id',
'booking_id',
'price',
]);
}])
->withSum('bookings', 'price')
// ->where('resorts.some_field', '<=', 123)
->get();
// ->toArray();
但不要忘记在您的父(Resort)模型中定义适当的关系:
public function bookings() {
return $this->hasMany(Booking::class, 'resort_id', 'id');
}
您还需要在孩子的(预订)迁移中定义“resort_id”外键:
$table->unsignedTinyInteger('resort_id')->nullable();
$table->foreign('resort_id')->references('id')
->on('resorts'); // ->onUpdate('cascade')->onDelete('cascade');
【讨论】: