I have a join query in mysql
SELECT c.*, r.*
FROM court c
LEFT JOIN reservations r
ON c.`id` = r.`court_id`
AND `start_time` < '2016-01-20 11:30:00'
AND `end_time` > '2016-01-20 11:00:00'
WHERE `start_time` IS NULL;
For reference:
reservations.rb
belongs_to court
fields: start_time,end_time, court_id
courts.rb
has_many reservations
fields: id, name
I've tried to convert this to rails, but can't seem to do it. I've tried Courts.join(:reservations).on("start_time<'2016-01-20 11:00:00'")
but this doesn't work
The converted version will be:
Courts.joins('LEFT JOIN reservations ON courts.id = reservations.id')
.where('reservations.start_time < ? AND reservations.end_time > ?', '2016-01-20 11:30:00', '2016-01-20 11:00:00')
.where(courts: {start_time: nil})
Note that joins
in default is INNER JOIN
, so we need to explicitly point out LEFT JOIN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.