본문 바로가기
MySql

MySQL Laravel 쿼리 빌더로 WHERE 조건 주위에 대괄호를 추가하는 방법

by 베이스 공부 2020. 12. 8.
반응형

Laravel 쿼리 빌더를 사용하여 사용자의 필터 선택에 따라 데이터를 동적으로 필터링하고 있습니다.

 $query = DB::table('readings');
 foreach ($selections as $selection) {
   $query->orWhere('id', $selection);
 }
 $query->whereBetween('date', array($from, $to));
 $query->groupBy('id');

SQL을 살펴보면 다음과 같은 결과가 나타납니다.

select count(*) as `count` from `readings` where `id` = 1 or id` = 2 and `date` between "2013-09-01" and "2013-09-31" group by `id`;

그러나 내가 필요한 것은 다음과 같습니다 (또는 문을 괄호로 묶음).

select count(*) as `count` from `readings` where (`id` = 1 or id` = 2) and `date` between "2013-09-01" and "2013-09-31" group by `id`;

Laravel 쿼리 빌더로 WHERE 조건 주위에 대괄호를 어떻게 추가합니까?

 

해결 방법

 


 $query = DB::table('readings');
 $this->builder->orWhere(function($query) use ($selections)
 {
    foreach ($selections as $selection) {
       $query->orWhere('id', $selection);
    }
 });
 $query->whereBetween('date', array($from, $to));
 $query->groupBy('id');

 

참조 페이지 https://stackoverflow.com/questions/22694866

 

 

반응형

댓글