Laravel 4先进的wheres

时间:2014-10-21 11:21:13

标签: laravel laravel-4 query-builder

我的查询在mySQL中完美运行,但是我很难在laravel查询构建器中使用高级数据库。

有人可以协助转换吗?

到目前为止,我有:

LARAVEL

$start_request = '2014-12-18 09:00';
$end_request = '2014-12-18 10:00';

$events=  DB::table('events')
          ->where('hotel_id', 4)
          ->orWhere(function($query)
                {
                    $query->where($start_request, '<=', 'start_time')
                              ->where($end_request, '>', 'start_time');
                })
            ->orWhere(function($query)
                 {
                     $query->where($start_request, '>=', 'start_time')
                                ->where($end_request, '<', 'end_time');
                 })
            ->get();

mySQL的

SELECT id, title, description, start_time, end_time FROM events where hotel_id = 4 and (('2014-12-18 09:00' <= start_time and '2014-12-18 10:00' > start_time) 
       or ('2014-12-18 09:00' >= start_time and '2014-12-18 10:00' < end_time));

2 个答案:

答案 0 :(得分:1)

你能试试吗?

$start_request = '2014-12-18 09:00';
$end_request = '2014-12-18 10:00';

$events=  DB::table('events')
          ->where('hotel_id', 4)
          ->where(function($query) use($start_request, $end_request) {
                    $query->where(function($subquery) use($start_request, $end_request){
                        $subquery->where('start_time', '>=', $start_request)
                                 ->where('start_time', '<', $end_request);
                    });
                    $query->orWhere(function($subquery1) use($start_request, $end_request) {
                        $subquery1->where('start_time', '<=', $start_request)
                                ->where('end_time', '>', $end_request);
                    });

            })
            ->get();

答案 1 :(得分:1)

这样的事情应该可以胜任:

$start_request = '2014-12-18 09:00';
$end_request = '2014-12-18 10:00';

$events = DB::table('events')
    ->where('hotel_id', 4)
    ->where(function ($q) use ($start_request, $end_request) {
        $q->where(function ($query) use ($start_request, $end_request) {
            $query->where($start_request, '<=', 'start_time')
                ->where($end_request, '>', 'start_time');
        })
        ->orWhere(function ($query) use ($start_request, $end_request) {
            $query->where($start_request, '>=', 'start_time')
                ->where($end_request, '<', 'end_time');
        });
    })
    ->select('id', 'title', 'description', 'start_time', 'end_time')
    ->get();