我将 where 与多个 whereHas() 一起使用,但没有得到预期的结果。
这是我的代码
public function getCommunityScoreByUser($user,$category_id) {
$question_ids = $user->answers->pluck('question_id')->unique();
$specialities = $this->speciality
->whereHas('questions', function($qry) use($question_ids){
$qry->whereIn('questions.id', $question_ids);
})
->orwhereHas('caseStudies', function($qry) use($user) {
$qry->where('user_id', $user->id);
})
->where('is_active', 'Y')
->where('category_id',$category_id)
->withCount('answers')
->withCount(['answers as bestAnswerCount' => function ($query) {
$query->where('question_answer.is_accepted','Y');
}])
->with(['answers' => function ($query) {
$query->withCount(['votes' => function ($query) {
$query->where('count','1');
}]);
}])
->get();
foreach ($specialities as $speciality => $key) {
$votes_count = 0;
foreach ($key->answers as $key1 => $value) {
$votes_count += $value->votes_count;
}
$key->votesCount = $votes_count;
$key->totalVotes = (3*$key->bestAnswerCount)+$votes_count+$key->case_study_votes_count;
}
return $specialities;
}
Run Code Online (Sandbox Code Playgroud)
预期结果
我想获取有问题或案例研究的专业,它应该符合标准 ->where('category_id',$category_id)
实际结果
$specialities包含问题或案例研究,但它不检查category_id. 相反,它获取$specialities所有类别。但是,如果我删除其中一个 whereHas,那么它就可以完美运行。
请帮我找到解决方案。
你得到的结果是由于orWhereHas. 使用您当前的声明,它将获得所有有问题的专业,或者它有案例研究的地方等等。
您想要做的是将 限制or为仅whereHas声明。
为此,您可以执行以下操作:
$specialities = $this->speciality
->where(function ($qry) use ($question_ids, $user) {
$qry->whereHas('questions', function ($qry) use ($question_ids) {
$qry->whereIn('questions.id', $question_ids);
})->orwhereHas('caseStudies', function ($qry) use ($user) {
$qry->where('user_id', $user->id);
});
})
->where('is_active', 'Y')
->where('category_id', $category_id)
->withCount('answers')
->withCount(['answers as bestAnswerCount' => function ($query) {
$query->where('question_answer.is_accepted', 'Y');
}])
->with(['answers' => function ($query) {
$query->withCount(['votes' => function ($query) {
$query->where('count', '1');
}]);
}])
->get();
Run Code Online (Sandbox Code Playgroud)
这将做的只是将whereHas's包装在自己的位置,以便独立对待它们。
| 归档时间: |
|
| 查看次数: |
835 次 |
| 最近记录: |