这是模型查询的简化版本:User::select('users.*') ->when(!empty($this->searchInput['search[term]']), function ($query) { return $query->where( 'biography', 'LIKE', '%' . $this->searchInput['search[term]'] . '%' ); }) ->when(!empty($this->searchInput['search[location]']), function ($query) { return $query->where( 'country_id', $this->searchInput['search[location]'] ); }) ->when(!empty($this->searchInput['engagement']), function ($query) { foreach ($this->searchInput['engagement'] as $key => $value) { if ($key === array_key_first($this->searchInput['engagement'])) { $query->whereBetween('engagement_rate', $value); } else { $query->orWhereBetween('engagement_rate', $value); } } });(如果您想知道,我正在使用$key === array_key_first以确保第一次BETWEEN使用AND,然后OR根据用户的选择使用)这等同于以下 SQL 查询:SELECT `users`.*FROM `users`WHERE `country_id` = '31' AND `engagement_rate` BETWEEN '6' AND '20' OR `engagement_rate` BETWEEN '3.5' AND '6'in whereBetweenEloquent 不包含方括号,因此 country_id 选择器会被忽略。我需要最终的 SQL 语句如下(带括号):SELECT `users`.*FROM `users`WHERE `country_id` = '31' AND (`engagement_rate` BETWEEN '6' AND '20' OR `engagement_rate` BETWEEN '3.5' AND '6')我的问题:如何更改我的 Eloquent 查询以反映上述内容?
1 回答
MM们
TA贡献1886条经验 获得超2个赞
在and子句中添加参数组:whereBetween
orWhereBetween
User::select('users.*')
// ...
->when(!empty($this->searchInput['engagement']), function ($query) {
query->where(function ($q) {
foreach ($this->searchInput['engagement'] as $key => $value) {
if ($key === array_key_first($this->searchInput['engagement'])) {
$q->whereBetween('engagement_rate', $value);
} else {
$q->orWhereBetween('engagement_rate', $value);
}
}
});
});
- 1 回答
- 0 关注
- 133 浏览
添加回答
举报
0/150
提交
取消