Search code examples
laraveleloquentwherehas

How can I implement Laravel Eloquent wherehas count question?


I have bookings and addon table.

bookings has many addons.

I want to get bookings with addon type Optional Tour

I tried this

 $bookings = Booking::with([
        "add_ons",  
         ])
        ->whereHas("add_ons",function($q){
            $q->where("type","<>" ,AddOn::T_OPTIONAL_TOUR);
        })

which obviously not working. how can i get only bookings with no optional tour addon?

here is table infomation

bookings

id
name

Booking_add_ons

id
booking_id
add_on_id

add_ons

id
type
add_name

Solution

  • Use whereDoesntHave():

    $bookings = Booking::with('add_ons')
        ->whereDoesntHave('add_ons', function($q) {
            $q->where('type', '=', AddOn::T_OPTIONAL_TOUR);
        })->get();