How to get available dates with reservations?
I开发者_开发百科 am trying to build a system which lets users reserve a item, let's say a laptop..
My table looks like this:
Table 'items'
id int(20) PK auto_increment
type int(20) FK(types.id)
name varchar(200)
Table 'types'
id int(20) PK auto_increment
name varchar(200)
Table 'reservations'
id int(20) PK auto_increment
user int(20) FK(users.id)
startDate datetime
endDate datetime
Lets say I have 1 type (laptops) and 3 laptops all with the same specs, and a user just wants to reserve one laptop. How would I get all available dates for just a laptop ?
I dont mind how this is reached, either via PHP or MySQL, I just intend on letting users have a list with available dates for the given type of item..
If your reservation form prompts for $start and $end date/times for the reservation, this query will tell which laptops are available throughout the period specified by those two dates:
SELECT items.id, items.name
FROM items
LEFT JOIN types ON items.type = types.id
LEFT JOIN reservations ON reservations.item_id = items.id
WHERE (((reservations.endDate NOT between $start AND $end) and
(reservations.startDate NOT between $start AND $end)) or
(reservations.id IS NULL)) and
(types.id = $laptop_type_id)
The first two between
clauses will find any laptops whose start/end dates do not fall withing the requested start/end dates - e.g. they're reserved, but are available in the specified time range. The null check will find any laptops that not reserved at all. And the types.id check restricts the search to only laptops.
精彩评论