问题描述
我有 3 个表,分别是 Resort
、Booking
、Expense
,这些表是连接关系。代码如下,
$resorts = Resort::where('status',1)->with('bookings')->withSum('bookings','amount')
->with('expenses')->withSum('expenses','amount')->get();
我想使用 date
字段对该表进行排序。我如何在此查询中使用 wherebetween
进行预订和费用?
解决方法
你可以像这样在 with()
中传递数组
$resorts = Resort::where('status',1)
->with(
['bookings' => function ($q) {
$q->wherebetween('colName',['startDate','endDate']);
}]
)->withSum('bookings','amount')
->with(
['expenses' => function ($q) {
$q->wherebetween('colName','endDate']);
}]
)->withSum('expenses','amount')
->get();
参考链接 https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads