Laravel 使用WhereRaw on集合忽略关系

Laravel 使用WhereRaw on集合忽略关系,laravel,Laravel,我走了一条路线去搜索一个特定的收藏——顾客 客户模型 public function location() { return $this->belongsTo('App\Location'); } 位置模型 public function customers() { return $this->hasMany('App\Customer'); } 在索引页面上,我只是用$location->customers() $location来自模型路由绑定 这是我的搜索控

我走了一条路线去搜索一个特定的收藏——顾客

客户模型

public function location() {
    return $this->belongsTo('App\Location');
}
位置模型

public function customers() {
    return $this->hasMany('App\Customer');
}
在索引页面上,我只是用
$location->customers()

$location
来自模型路由绑定

这是我的搜索控制器:

if ($request->input('search') != null) {
    $customers = $location->customers();
    
    $search = strtoupper($request->input('search'));
    $searchQuery = 'UPPER(email) LIKE (?) OR CONCAT(UPPER(first_name), " ", UPPER(last_name)) LIKE (?)';

    $customers = $location->customers()->whereRaw($searchQuery, ["%{$search}%", "%{$search}%"]);

    $customers = $customers->paginate();
}

return response()->json(['results' => $customers], 200);
当执行搜索时,在某些情况下,我得到的结果是原来的10倍,因为它抓住的是所有客户,而不是特定的位置关系


如何使
whereRaw
使用关系?

这是因为
条件将查询弄乱了。为了避免这种情况,请将这两个查询部分用括号括起来
()

$searchQuery='(大写(电子邮件)如(?)或CONCAT(大写(名字),“”,大写(姓氏))如(?);
雄辩的建设者方法:

$customers=$location->customers()->where(函数($query)使用($search){
$query->whereRaw('UPPER(email)LIKE(?),[“%{$search}%”);
$query->orWhereRaw('CONCAT(大写(姓氏),“”,大写(姓氏))如(?),[“%{$search}%”);
});
解释

逻辑表达式示例:

firstCondition和&secondCondition | | thirdCondition

在上面的示例中,表达式
thirdCondition
甚至不关心
firstCondition
secondCondition
,因为
|

因此,如果要用第二个条件检查第三个条件,则必须用括号明确地将这两个条件括起来

firstCondition&(secondCondition | | thirdCondition)


同样的逻辑也适用于mysql查询。

什么是
$location
?当查询被发送到数据库时,它是什么样子的?