본문 바로가기
MySql

MySQL OR 및 AND와 where 절을 사용한 Laravel eloquent SQL 쿼리

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

나는 SQL AND가 연속적인 where 절에 의해 달성 될 수 있음을 알고 있습니다. 및 OR with where (condition, 'OR'). I want to choose all the messages from message table where sentTo = editor_id AND sentFrom= currentUser_id OR where sentTo = currentUser_id AND sentFrom = editor_id. 결과를 얻으려는이 쿼리가 있습니다.

    $this->data['messages'] = Message::where(function ($query) use($uId) {
        $query->where('sentTo', '=', $this->data['currentUser']->id)
            ->orWhere('sentFrom', '=', $uId);
            })
    ->where(function ($query) use($uId){
             $query->where('sentTo', '=', $uId)
                     ->orWhere('sentFrom', '=', $this->data['currentUser']->id);
            })
    ->get();

어떻게 할 수 있습니까? 조언 부탁드립니다.

 

해결 방법

 

원하는 연산자 우선 순위를 알기 위해 괄호를 제공하지 않았기 때문에 약간 혼란 스럽습니다.

WHERE (editor_id = $ editorId AND sentFrom = $ currentUserId) OR (sentTo = $ currentUserId AND sentFrom = $ editorId) 를 원한다고 가정하면 최신 버전의 Laravel을 사용하면 다음을 수행 할 수 있습니다.

    Message::where(['editor_id' => $editorId, 'sentFrom' => $currentUserId])
    ->orWhere(['sentTo' => $currentUserId, 'sentFrom' => $editorId])->get();

클로저를 사용할 필요가 없습니다.

 

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

 

 

반응형

댓글