In Laravel 4.2 I have a model called Product with many-to-many relationshis to other models like Country or Category. I want to filter out products that are "incomplete", which means they have no connected countries or no connected categories. I can use whereDoesntHave() method to filter out one relation. When I use it two times in one query it creates AND condition, but I need OR. I can't find orWhereDoesntHave() method in API documentation. I can't pass multiple relations as arguments because it expects first argument to be a string.

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

有没有办法在有多个OR个条件的情况下达到whereDoesntHave()分呢?

推荐答案

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

$products = Product::doesntHave('categories')->doesntHave('countries', 'or')->get();

Actually you only need whereDoesntHave if you want to pass in a closure to filter the related models before checking if any of them exist. In case you want to do that you can pass the closure as third argument:

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

Laravel相关问答推荐

如何判断用户是否已登录Laravel

为什么只删除了最后一个Like,而没有删除选中的?

API GET 请求得到与数据库记录不同的结果

mysql 加入 ON 和 AND 到 laravel eloquent

如何访问 Validator::extend 中的其他输入属性?

Laravel 5 如何全局设置 Cache-Control HTTP 标头?

Laravel 5.3 auth 判断构造函数返回 false

Laravel 查询构建器 - 如何按别名分组,或进行原始 groupBy

如何在新安装时指定 Lumen(或 Laravel)版本?

SQLSTATE [01000]:警告:1265 列的数据被截断(truncated)

Laravel 控制器构造

如何处理 php (Laravel api) 和 javascript (AngularJS) 之间的日期时间

使用 Laravel 创建新项目会引发异常

Laravel Mail 发送Electron邮件但返回 false

反向代理后面的 Laravel 路由

Laravel - DecryptException:'MAC 无效'

Laravel 5 事件处理程序未触发

Laravel Eloquent 模型属性

将值插入隐藏输入 Laravel Blade

如何使用 Postman 处理 Laravel $_POST 请求