Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel whereHas include no relation

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

  • Store

  • Product

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

like image 491
bazi Avatar asked Dec 26 '16 04:12

bazi


1 Answers

Product::doesntHave('stores')->orWhereHas('stores', function($query) {
    $query->where('id', '=', $store_id);
})->get();
like image 191
Alex Lukinov Avatar answered Sep 21 '22 12:09

Alex Lukinov