2017-09-25 182 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雄辯做同樣的事情。 通過使用下面的代碼,我沒有得到與上面相同的結果。下面的查詢有問題。

$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

WHERE條件不正確使用,你可以試試這個:

$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); 
    }); 
});