猿问

在 Laravel 中向 BETWEEN 查询添加括号?

这是模型查询的简化版本:


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 查询以反映上述内容?


慕雪6442864
浏览 134回答 1
1回答

MM们

在and子句中添加参数组:whereBetweenorWhereBetweenUser::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);            }        }    });});
随时随地看视频慕课网APP
我要回答