laravel whereHas 不包含任何关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41326513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:00:15  来源:igfitidea点击:

laravel whereHas include no relation

laraveleloquent

提问by bazi

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_store. 有些商店没有任何产品。我如何查询所有产品,即使是那些不属于任何商店的产品,例如:

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

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 mentionthis

但随着laravel文档提到这个

Retrieves all products with at least one store

检索至少有一家商店的所有产品

回答by Alex Lukinov

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