【问题标题】:Eloquent havingRaw problems雄辩的有原始问题
【发布时间】:2017-01-28 08:35:58
【问题描述】:

我有 2 个 SQL 表:一个代表旅行,另一个代表这些旅行的预订。结构如下:

tours
(int) id 
(int) max_participants
(int) state

bookings
(int) id
(fk)  tour
(fk)  date
(int) num_passengers

bookings 表有一个 FK 日期,但该表非常简单且不重要,因为它不会给我带来任何麻烦。

现在我需要过滤我的旅行,只向客户显示仍然可以容纳他想要的乘客数量的旅行。因此,假设一次旅行的 max_participants 为 50,并且某个日期的多次预订中已经有 48 名 num_passengers,我必须拒绝额外预订 3 名乘客(如 48+3>=50)但接受额外预订 2 名乘客(如 48+2>=50)。

我提出了这个 SQL,它工作得很好(为了便于阅读,一些值是硬编码的,但它们正在使用变量):

select * from `tours` where `state` = 1
and exists (select * from `bookings` where `bookings`.`tour` = `tours`.`id` and `date` = 280 having SUM(num_passengers) + 2 <= `tours`.`max_participants`)

当我尝试用 eloquent 做到这一点时,我做到了这一点:

$tours = Tour::where('state', 1)
->whereHas('toursBookings', function ($query) use ($request, $date) {
    return $query->where('date', $date->id)
        ->havingRaw('SUM(num_passengers) + ' . $request->get('filter_number_passengers') . ' <= ?', [50]);
})
->get();

这些作品就像一个魅力,并完成了它应该做的所有事情,但数字 50 是硬编码的!这是一个严重的问题,因为每个巡演的 max_participants 数量不同。

谁能找到解决这个问题的方法并取消对 50 的硬编码?它应该是tours.max_participants,就像在 SQL 中一样。

【问题讨论】:

  • 你可以像$date一样传递变量$max_participants。对吗?

标签: sql laravel eloquent


【解决方案1】:

如果我理解正确,你可以这样做

$max_participants = [50];
$tours = Tour::where('state', 1)
->whereHas('toursBookings', function ($query) use ($request, $date,$max_participants) {
    return $query->where('date', $date->id)
        ->havingRaw('SUM(num_passengers) + ' . $request->get('filter_number_passengers') . ' <= tours.max_participants');
})
->get();

【讨论】:

  • 嗯,不完全是因为 $max_participants 是 tours 表中的一个字段,所以它需要从一个旅游到另一个旅游。假设 tour1 的 max_participants 为 50,tour2 的 max_participants 为 30,tour3_ 的 max_participants 为 90。Eloquent 需要为每种情况使用正确的值,而不是硬编码的值...
  • 这种情况下可以直接放列名
猜你喜欢
  • 2018-01-31
  • 1970-01-01
  • 2015-11-01
  • 2016-07-20
  • 2019-03-17
  • 2020-07-03
  • 2014-10-18
  • 2016-09-14
相关资源
最近更新 更多