我有2个模型1)预订2)BookingPeriod
预订has_many_booking_periods和booking_period属地_to预订
current_resource_owner.bookings.includes(
:slot, :booking_periods, plan_location: [:plan, content: [:original_image]]
).left_outer_joins(
:booking_periods, plan_location: :likes
).select(
'bookings.*, COUNT(plan_locations_likes.id) as likes_count, COUNT(booking_periods.id) as booking_count'
)
.where(
"booking_periods.to > ?", Date.current
)
.group(
'bookings.id'
)
如果所有预订期都在将来,我需要选择预订记录。例如,如果预订1有3个预订期。和2个预订期日期已经过去。并且将来有一个booking_period,我不想要该记录,但是从上面的查询中我得到了该记录。
我认为要获得正确的记录,我需要这样查询
current_resource_owner.bookings.includes(
:slot, :booking_periods, plan_location: [:plan, content: [:original_image]]
).left_outer_joins(
:booking_periods, plan_location: :likes
).select(
'bookings.*, COUNT(plan_locations_likes.id) as likes_count, COUNT(booking_periods.id) as booking_count'
)
.where(
"booking_periods.to #{params[:booking] == 'previous_bookings' ? '<' : '>'} ?", Date.current
)
.group(
'bookings.id'
).having(
"count(booking_periods.id) >= ?", "SELECT
COUNT(booking_periods.id) from bookings INNER JOIN
booking_periods ON bookings.id = booking_periods.id"
)
基本上,我需要做一些事情,例如预订的预订期间数不应小于我按查询分组后得到的COUNT(booking_periods)
。