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
->whereHas()
: laravel/docs/12.x/… – Tim Lewis Commented Mar 27 at 18:30->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:07Person
, and a self-referencing relationshipchildren
, then you could doPerson::where('gender', 'male')->whereDoesntHave('children', function ($query) { $query->where('employed', true })->get();
(or similar). What's the difference between aDad
,Son
andDaughter
Model in your code? You're duplicating a lot of logic for no real gains... – Tim Lewis Commented Mar 27 at 19:10本文标签: laravelHow to find model with condition on multiple relationshipStack Overflow