问题
I need to display reproductions based on Gender Condition
Reproduction Table:
$table->bigIncrements('id');
$table->unsignedInteger('father_id');
$table->unsignedInteger('mother_id');
...
I need to retrieve reproductions according to the gender
User.php
public function reproductions(){
if($this->gender == 'm'){
return $this->hasMany(Reproduction::class, 'father_id');
}else{
return $this->hasMany(Reproduction::class, 'mother_id');
}
}
Reproduction Table:
id father_id mother_id
1 1 2
2 1 3
3 1 4
When I retrieve reproduction for User with id 1, it needed to display 3 reproductions but it returns null collection
$firstUser = User::find(1); // User Id with 1 has gender m
dd($firstUser->reproductions->count()); // Should return 3 but returns null collection
回答1:
you can create two different relationships.
public function maleReproductions(){
return $this->hasMany(Reproduction::class, 'father_id');
}
public function feMaleReproductions(){
return $this->hasMany(Reproduction::class, 'mother_id');
}
now based on $user
you can attach relationship.
$productions = [];
$user = User::where('id',1)->first();
if($user->gender == 'm'){
$productions = $user->maleProductions;
} else {
$productions = $user->feMaleProductions;
}
for collection of users, attach both relationship. and access specific based on condition.
$users = User::with('maleReproductions', 'femaleReproductions')->get();
foreach($users as $user){
if($user->gender == 'm'){
$productions = $user->maleProductions;
} else {
$productions = $user->feMaleProductions;
}
}
来源:https://stackoverflow.com/questions/60826319/laravel-create-hasmany-relationship-based-on-condition