【问题标题】:Laravel eloquent Scope ANDLaravel 雄辩的范围和
【发布时间】:2026-02-08 06:10:02
【问题描述】:

我有 1 个包含字段(标题、cat1、cat2、cat3、cat4、位置、城市、区域)的表格邮寄广告

现在我从帖子广告表中传递 2 个值 category_id 和位置搜索结果。

这是我的代码 // 搜索类别、位置

public function scopeLocationSearch($query,$post_location,$category_id) 
{
    return $query->category($category_id)->location($post_location)->get();     
}

category 和 location 范围是 Scopes 如下:

public function scopeCategory($query,$cat_id)
{
    return $query->where('cat1', $cat_id)
                 ->orWhere('cat2', $cat_id)
                 ->orWhere('cat3', $cat_id)
                 ->orWhere('cat4', $cat_id);
}

public function scopeLocation($query,$location)
{
    return $query->where('location','LIKE','%'.$location.'%')
                 ->orWhere('city','LIKE', '%'.$location.'%')
                 ->orWhere('area','LIKE', '%'.$location.'%');
}

这些范围单独给出了我想要的结果,但是当我调用 locationsearch 时,它给出了错误的结果。它只是为我提供OR 结果,但我想要AND 结果。

谢谢

【问题讨论】:

  • 而不是->orWhere(...),只需使用另一个->where(...)。 Laravel 将使用 AND 比较器。
  • 类别和位置有2组,有(或所有类别之间)和(或所有位置之间)
  • 我现在明白了。在你的 scopeLocationSearch 中试试这个:$query->where(function($q){ $q->location(...);})->where(function($q){ $q->category(...)});
  • 试过 $query->where(function($q,$post_location){ $q->location($post_location);})->where(function($q,$category_id){$ q->category($category_id);});但现在出现错误缺少 App\PostAd::App\{closure}() 的参数 2

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

当您使用or 运算符作为条件时,您应该将整个条件包装到闭包中,以确保执行有效的查询。

你的方法应该是这样的:

public function scopeCategory($query,$cat_id)
{
    return $query->where(function($query) use ($cat_id) {
                  $query->where('cat1', $cat_id)
                 ->orWhere('cat2', $cat_id)
                 ->orWhere('cat3', $cat_id)
                 ->orWhere('cat4', $cat_id);
                 });
}

public function scopeLocation($query,$location)
{
    return $query->where(function($query) use ($location) {
                  $query->where('location','LIKE','%'.$location.'%')
                 ->orWhere('city','LIKE', '%'.$location.'%')
                 ->orWhere('area','LIKE', '%'.$location.'%');
           });
}

【讨论】: