A JOIN With Additional Conditions Using Query Builder or Eloquent

后端 未结 6 693
抹茶落季
抹茶落季 2020-12-04 09:08

I\'m trying to add a condition using a JOIN query with Laravel Query Builder.



        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 09:29

    You can replicate those brackets in the left join:

    LEFT JOIN bookings  
                   ON rooms.id = bookings.room_type_id
                  AND (  bookings.arrival between ? and ?
                      OR bookings.departure between ? and ? )
    

    is

    ->leftJoin('bookings', function($join){
        $join->on('rooms.id', '=', 'bookings.room_type_id');
        $join->on(DB::raw('(  bookings.arrival between ? and ? OR bookings.departure between ? and ? )'), DB::raw(''), DB::raw(''));
    })
    

    You'll then have to set the bindings later using "setBindings" as described in this SO post: How to bind parameters to a raw DB query in Laravel that's used on a model?

    It's not pretty but it works.

提交回复
热议问题