2016-12-26 102 views
1

如何查詢關係並仍然包含沒有關係的模型?有兩種型號laravel where has include no relation

  • 商店

  • 產品

代碼

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

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

和數據透視表連接它們稱爲product_store。有些商店沒有任何產品。如何查詢所有的產品,即使是那些誰不屬於任何商店,如:

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

這是我目前如何做到這一點。

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

但隨着laravel docs mention

檢索所有產品與至少一個商店

回答

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

如何過濾'$產品 - > stores'到只有一個。即$ store_id – bazi

+0

此查詢爲您提供的商店商品是$ store_id –

+0

是的。它也給了我沒有任何商店的產品。但我也希望產品不在$ store_id和其他商店 – bazi

相關問題