bazi
bazi

Reputation: 1876

laravel whereHas include no relation

How can i query relationship and still include models that has no relationships? There are two models

code

// Store
public function products() {
   $this->belongsToMany('App\Store');
}

// Product
public function stores() {
   $this->belongsToMany('App\Product');
}

and a pivot table to connect them called product_store. Some stores don't have any products. How do i query all products, even those who doesn't belong to any store like:

Product::where('store.id', '=', 1)->get()

this is how i currently do it.

Product::whereHas('stores', function($query) {
    $query->where('id', '=', $store_id);
});

but as the laravel docs mention this

Retrieves all products with at least one store

Upvotes: 14

Views: 23790

Answers (1)

Alex Lukinov
Alex Lukinov

Reputation: 785

Product::doesntHave('stores')->orWhereHas('stores', function($query) {
    $query->where('id', '=', $store_id);
})->get();

Upvotes: 27

Related Questions