Skip to content
Advertisement

Eloquent “where” on relationship returns wrong models

I have this method on my model “Employer”:

    public function job_offers() {
        return $this->hasMany('AppJobOffer');
    }

    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?

Advertisement

Answer

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]
        ]);
    });
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement