我有以下AR查询返回一个房间数组(在给定的时间段内不可用的房间):
rooms = Room.joins(:bookings).where("(bookings.start_date >= ? AND bookings.start_date <= ?) OR (bookings.end_date >= ? AND bookings.end_date <= ?) OR (bookings.start_date <= ? AND bookings.end_date >= ?)", from, to, from, to, from, to)
我想修改该查询,以便返回所有其他房间;这是在请求的时间段内可用的那些。正确的结果如下:
all_rooms = Room.all
available_rooms = all_rooms - rooms
但我直接想在一个查询中获取可用的房间。我已经添加了一个.not但它没有给我正确的结果:
rooms = Room.joins(:bookings).where.not("(bookings.start_date >= ? AND bookings.start_date <= ?) OR (bookings.end_date >= ? AND bookings.end_date <= ?) OR (bookings.start_date <= ? AND bookings.end_date >= ?)", from, to, from, to, from, to)
我该如何修改查询?
答案 0 :(得分:1)
让我们说:
A = (bookings.start_date >= ? AND bookings.start_date <= ?)
B = (bookings.end_date >= ? AND bookings.end_date <= ?)
C = (bookings.start_date <= ? AND bookings.end_date >= ?)
first_logic = A or B or C
second_logic = not(first_logic) = not(A or B or C) = not(A) and not(B) and not(C)
available_rooms
是second_logic
的条件,因此它会像:
available_rooms = Room.joins(:bookings)
.where.not("bookings.start_date >= ? AND bookings.start_date <= ?", from, to)
.where.not("bookings.end_date >= ? AND bookings.end_date <= ?", from, to)
.where.not("bookings.start_date <= ? AND bookings.end_date >= ?", from, to)