Laravel查询无法正常工作
问题描述:
我有简单的查询正常工作,但我希望它正常使用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);
});
});
它没有显示与上述相同的结果,让我知道如何使其与上面相同。
答
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);
});
});
你不没有正确使用“与”功能。该函数获取关系名称作为参数,不像“user。*” –
@GiacomoMasseroniChiaro,这是远程关系的语法。 – Devon
你不用功能正常,即用户。* – omkara