我正在尝试使用Laravel查询生成器的JOIN查询添加条件。
<?php
$results = DB::select('
SELECT DISTINCT
*
FROM
rooms
LEFT JOIN bookings
ON rooms.id = bookings.room_type_id
AND ( bookings.arrival between ? and ?
OR bookings.departure between ? and ? )
WHERE
bookings.room_type_id IS NULL
LIMIT 20',
array('2012-05-01', '2012-05-10', '2012-05-01', '2012-05-10')
);
我知道我可以使用原始表达式,但随后会有SQL注入点。我已经使用查询生成器尝试了以下操作,但是生成的查询(显然是查询结果)不是我想要的:
$results = DB::table('rooms')
->distinct()
->leftJoin('bookings', function ($join) {
$join->on('rooms.id', '=', 'bookings.room_type_id');
})
->whereBetween('arrival', array('2012-05-01', '2012-05-10'))
->whereBetween('departure', array('2012-05-01', '2012-05-10'))
->where('bookings.room_type_id', '=', null)
->get();
这是Laravel生成的查询:
select distinct * from `room_type_info`
left join `bookings`
on `room_type_info`.`id` = `bookings`.`room_type_id`
where `arrival` between ? and ?
and `departure` between ? and ?
and `bookings`.`room_type_id` is null
如您所见,查询输出没有结构(特别是在JOIN范围内)。是否可以在JOIN下添加其他条件?
如何使用Laravel的查询生成器构建相同的查询(如果可能),最好是使用Eloquent,还是应该保留在DB :: select中?
and arrival >= ? and arrival <= ? and departure >= ? and departure <= ?
改为具有连接条件AND ( r.arrival between ? and ? OR r.departure between ? and ? )
(请注意该OR
子句)。这将添加其他行,以致不应存在的行。我想不可能使用QB在联接中生成所有类型的条件。