2017-09-25 2 views
0

간단한 쿼리가 제대로 작동하지만 ORM을 사용하여 올바르게 작동하게하고 싶습니다.Laravel 쿼리가 제대로 작동하지 않습니다.

나는 다음과 같은 SQL 쿼리가 :

SELECT career_solutions.*, 
    users.username, 
    users.profile_picture 
FROM career_solutions 
    INNER JOIN users 
      ON users.id = career_solutions.user_id 
    INNER JOIN privacy_settings 
      ON privacy_settings.user_id = users.id 
WHERE career_solutions.topic_category_id = $categoryid 
    AND ((privacy_settings.career_solutions = 0 
      AND public = 1) 
      OR ((users.id IN (SELECT contacts.contact_id 
          FROM contacts 
          WHERE contacts.user_id = $id) 
       OR users.id = $id))) 
ORDER BY date DESC 
LIMIT 5000 

내가 지금처럼 DB 외관의 선택 방법에 직접 쿼리를 전달 해요 : DB::select($aboveQuery);하고 잘 작동하고 있습니다.

나는 Laravel Eloquent를 사용하여 동일한 작업을 수행하려고합니다. 다음 코드를 사용하여 위와 같은 결과를 얻지는 못합니다. 아래 쿼리에 문제가 있습니다.

$career_solution = CareerSolution::with('user.role', 'user.privancy_setting', 'category', 'sub_category', 'country'); 

$career_solution = $career_solution->where(function ($query) { 
    $query->where('expires_at', '>=', date('Y-m-d')) 
     ->orWhere('expires_at', '=', '0000-00-00'); 
}); 

$career_solution = $career_solution->Where(function ($query1) use ($id) { 
    $query1->Where(function ($query2) use ($id) { 
     $query2->whereHas('user.privancy_setting', function ($query3) { 
      $query3->where('privacy_settings.career_solutions', '=', 0); 
     })->where('public', '=', 1); 
    })->orWhere(function ($query4) use ($id) { 
     $query4->whereHas('user.contact', function ($query5) use ($id) { 
      $query5->where('contacts.user_id', '=', $id); 
     })->orWhere('user_id', '=', $id); 
    }); 
}); 

위와 같은 결과가 표시되지 않습니다. 어떻게 위와 동일하게 만드는지 알려주세요.

+0

당신은 제대로 "와"기능을 사용하지 돈. 이 함수는 "user. *"와 같은 것이 아닌 관계 이름을 매개 변수로 가져옵니다. –

+0

@GiacomoMasseroniChiaro, 그것은 먼 관계에 대한 구문입니다. – Devon

+0

사용자가 제대로 기능을 사용하지 않습니다. * – omkara

답변

0

조건이 올바르게 사용되지 않은, 당신이 시도 할 수 :

$career_solution = CareerSolution::with('user.role', 'user.privancy_setting', 'category', 'sub_category', 'country'); 

$career_solution = $career_solution->where(function ($query) { 
    $query->where('expires_at', '>=', date('Y-m-d')) 
     ->orWhere('expires_at', '=', '0000-00-00'); 
}); 

$career_solution = $career_solution->where(function ($query1) use ($id) { 
    $query1->where(function ($query2) use ($id) { 
         // assuming that the relation name in User model is name public function privacy_setting .. 
     $query2->whereHas('user.privacy_setting', function ($query3) { 
      $query3->where('career_solutions', '=', 0); // You don't need to specify the table here only the table field you want 
     })->where('public', '=', 1); 
    })->orWhere(function ($query4) use ($id) { 
         // idem here the relation must be name contact 
     $query4->whereHas('user.contact', function ($query5) use ($id) { 
      $query5->where('user_id', '=', $id); // idem here 
     })->orWhere('user_id', '=', $id); 
    }); 
}); 
관련 문제