我确实有简单的查询正常工作但我希望它使用ORM正常工作。
我有以下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 Facade的select方法,如下所示:
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 :(得分: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);
});
});