Laravel whereDoesntHave() - 多个OR条件

Kaz*_*ikM 10 relationship laravel

在Laravel 4.2中,我有一个名为Product的模型,与其他模型(如Country或Category)有多对多的关系.我想过滤掉"不完整"的产品,这意味着它们没有连接的国家或没有连接的类别.我可以使用whereDoesntHave()方法来过滤掉一个关系.当我在一个查询中使用它两次时它会创建AND条件,但我需要OR.我orWhereDoesntHave()在API文档中找不到方法.我不能将多个关系作为参数传递,因为它期望第一个参数是一个字符串.

我需要这样的东西: $products = Product::whereDoesntHave('categories')->orWhereDoesntHave('countries')->get();

有没有办法达到whereDoesntHave()多种OR条件?

luk*_*ter 17

您可以使用doesntHave并指定布尔运算符:

$products = Product::doesntHave('categories')->doesntHave('countries', 'or')->get();
Run Code Online (Sandbox Code Playgroud)

实际上,只有whereDoesntHave在要检查是否存在相关模型之前,才需要传入闭包来过滤相关模型.如果你想这样做,你可以传递闭包作为第三个参数:

$products = Product::doesntHave('categories', 'or', function($q){
    $q->where('active', false);
})->doesntHave('countries', 'or')->get();
Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 12

从 Laravel 5.5 开始,有一个orWhereDoesntHave函数。

你可以这样使用它

Product::whereDoesntHave('categories', function($q){ //... })
       ->orWhereDoesntHave('countries', function($q){//...})
       ->get();
Run Code Online (Sandbox Code Playgroud)

从你的例子来看,你似乎没有使用 where 子句,所以你可以使用

Product::doesntHave('categories')
       ->orDoesntHave('countries')
       ->get();
Run Code Online (Sandbox Code Playgroud)


Had*_*azi 5

让 \xe2\x80\x99s 说我们有作者和书籍,具有 1-n 关系 \xe2\x80\x93 一个作者可以拥有一本或多本书。这里\xe2\x80\x99是它在app\\Author.php中的样子:

\n
 public function books()\n    {\n        return $this->hasMany(\\App\\Book::class, 'author_id');\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

现在,如果我们只想显示那些至少拥有一本书的作者怎么办?简单,有\xe2\x80\x99s方法has():

\n
$authors = Author::has('books')->get();\n
Run Code Online (Sandbox Code Playgroud)\n

同样,有一个相反的方法\xe2\x80\x99,如果我们只想查询作者而不查询任何书籍怎么办?使用 notthave():

\n
  $authors = Author::doesnthave('books')->get();\n
Run Code Online (Sandbox Code Playgroud)\n

它\xe2\x80\x99不仅方便,而且超级容易阅读和理解,即使你\xe2\x80\x99不是 Laravel 开发人员,对吗?

\n