Laravel: Create HasMany Relationship Based On Condition

妖精的绣舞 提交于 2021-01-29 19:45:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!