admin管理员组

文章数量:1357312

I have the following model with two one-to-many relationship:

class Dad extends Model
{
    public function sons()
    {
        return $this->hasMany('App\Models\Son', 'dad_id');
    }

    public function daughters()
    {
        return $this->hasMany('App\Models\Daughter', 'dad_id');
    }
}

Each son/daughter model can be either employed or unemployed. The following query can find dad with employed son(s) or employed daughter(s):

$dads = \App\Models\Dad::whereHas('sons', function (Builder $query) {

    $query->where('employed', 1);

})->get();

My questions is, how can I find dads that don't have either employed sons or employed daughters?

I have the following model with two one-to-many relationship:

class Dad extends Model
{
    public function sons()
    {
        return $this->hasMany('App\Models\Son', 'dad_id');
    }

    public function daughters()
    {
        return $this->hasMany('App\Models\Daughter', 'dad_id');
    }
}

Each son/daughter model can be either employed or unemployed. The following query can find dad with employed son(s) or employed daughter(s):

$dads = \App\Models\Dad::whereHas('sons', function (Builder $query) {

    $query->where('employed', 1);

})->get();

My questions is, how can I find dads that don't have either employed sons or employed daughters?

Share Improve this question edited Mar 27 at 18:42 DarkBee 15.5k8 gold badges72 silver badges117 bronze badges asked Mar 27 at 18:29 Zhiyong LiZhiyong Li 5293 silver badges16 bronze badges 6
  • To filter by a relationship, you need to use ->whereHas(): laravel/docs/12.x/… – Tim Lewis Commented Mar 27 at 18:30
  • @TimLewis you are right. I updated the question accordingly. But the basic question remains if we can filter by multiple relationship with conditions. – Zhiyong Li Commented Mar 27 at 18:41
  • 2 Yes. ->whereHas()->orWhereHas(); like any other query operation in Laravel, you can chain them as many times as you need to fulfil your requirements – Tim Lewis Commented Mar 27 at 19:07
  • 1 Honestly though; you've got a data structure problem... You only need a single model, Person, and a self-referencing relationship children, then you could do Person::where('gender', 'male')->whereDoesntHave('children', function ($query) { $query->where('employed', true })->get(); (or similar). What's the difference between a Dad, Son and Daughter Model in your code? You're duplicating a lot of logic for no real gains... – Tim Lewis Commented Mar 27 at 19:10
  • 2 Sweet! No problem then; there was a question asked in the last week that had the same data structure (Dad, Son, Daughter), that's the only reason I even brought it up; it was fresh in my memory

    本文标签: laravelHow to find model with condition on multiple relationshipStack Overflow