在Laravel4.2中,我有一个名为“产品”的模型,它与其他型号如国家或类别有着多到多的关系。我想过滤掉那些“不完整”的产品,这意味着它们没有相互关联的国家,也没有相互关联的类别。我可以使用whereDoesntHave()
方法过滤掉一个关系。当我在一个查询中使用它两次时,它会创建AND
条件,但我需要OR
。我在API文档中找不到orWhereDoesntHave()
方法。我不能将多个关系作为参数传递,因为它希望第一个参数是一个字符串。
我需要这样的东西:$products = Product::whereDoesntHave('categories')->orWhereDoesntHave('countries')->get();
有什么方法可以在多个whereDoesntHave()
条件下实现OR
?
发布于 2015-01-21 12:11:26
您可以使用doesntHave
并指定布尔运算符:
$products = Product::doesntHave('categories')->doesntHave('countries', 'or')->get();
实际上,在检查相关模型是否存在之前,您只需要传入一个闭包来筛选相关模型。如果您想这样做,可以将闭包作为第三个参数传递:
$products = Product::doesntHave('categories', 'or', function($q){
$q->where('active', false);
})->doesntHave('countries', 'or')->get();
发布于 2019-04-18 12:28:44
从Laravel5.5开始,就有一个orWhereDoesntHave函数。
你可以这样用它
Product::whereDoesntHave('categories', function($q){ //... })
->orWhereDoesntHave('countries', function($q){//...})
->get();
从您的示例来看,您似乎没有使用where子句,所以您可以只使用
Product::doesntHave('categories')
->orDoesntHave('countries')
->get();
发布于 2015-01-21 12:10:15
使用
Product::whereDoesntHave('categories')->doesntHave('countries', 'or')->get();
Laravel源代码:
whereDoesntHave https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#L654在内部调用https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#L628。
https://stackoverflow.com/questions/28065566
复制相似问题