Why does my relationship return results but not "withCount"? - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Friday, June 4, 2021

Why does my relationship return results but not "withCount"?

I have a model which has a relationship with "where" and "if". I need to retrieve all the models where the count of the relationship is > 1.

When I try to get it with "withCount", I end up having models which have relationships having 0 to the "shared_job_offers_count" when they should have 1. However, it works properly for some model.

I noticed that it happens when the "$this->isSubscribedPremium()" in the "if" is true.

RELATIONSHIP

    public function shared_job_offers() {
        if($this->isSubscribedPremium()) {
            return $this->hasMany('App\JobOffer')->where('disable_share', false);
        } else {
            return $this->hasMany('App\JobOffer')->where('manual_share', true);
        }
    }

RETRIEVING THE RESULTS
App\Employer::withCount('shared_job_offers')->get()->where('shared_job_offers_count', '>', 0)

RECAP:

withCount returns 0 for some models, 1 for the others it returns 0 mainly when "$this->isSubscribedPremium()" is true i can get all the proper relationships if I just retrieve it directly.

Any idea?



source https://stackoverflow.com/questions/67827011/why-does-my-relationship-return-results-but-not-withcount

No comments:

Post a Comment