如何查询关系并仍然包含没有关系的模型?有两种型号
代码
// 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 这个
最佳答案
Product::doesntHave('stores')->orWhereHas('stores', function($query) {
$query->where('id', '=', $store_id);
})->get();
关于laravel whereHas 不包含任何关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41326513/