mardi 24 mars 2020

Laravel: Create HasMany Relationship Based On Condition

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


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire