php - Eloquent "where" on relationship returns wrong models

I have this method on my model "Employer":
public function job_offers() {
return $this->hasMany('App\JobOffer');
}
public function shared_job_offers() {
return $this->job_offers()->where(function ($query) {
$query->where('subscription', 3)->where('disable_share', false);
})->orWhere(function ($query) {
$query->where('subscription', '!=', 3)->where('manual_share', true);
});
}
I thought it would work fine, but it ends up giving me models that aren't even related to my Model. Like, the id of the model is 37 and it gives me the relationships of all the models (like id 6).
Any idea of why this would happen?
Answer
Solution:
I think you are experiencing unexpected behaviour due to not grouping the where and orWhere in the same call. Does this work?
public function shared_job_offers() {
return $this->job_offers()->where(function ($query) {
$query->where([
['subscription', '=', 3],
['disable_share', '=', false]
])->orWhere([
['subscription', '!=', 3],
['manual_share', '=', true]
]);
});
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot access offset of type string on string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.