猿问

Laravel:根据条件创建 HasMany 关系

我需要根据性别条件显示复制品


再现表:


$table->bigIncrements('id');

$table->unsignedInteger('father_id');

$table->unsignedInteger('mother_id');

...

我需要根据性别检索复制品


用户.php


public function reproductions(){

    if($this->gender == 'm'){

        return $this->hasMany(Reproduction::class, 'father_id');

    }else{

        return $this->hasMany(Reproduction::class, 'mother_id');

    }

}

再现表:


id    father_id    mother_id


1         1            2


2         1            3


3         1            4

当我检索 ID 为 1 的用户的复制品时,它需要显示 3 个复制品,但它返回 null 集合


$firstUser = User::find(1); // User Id with 1 has gender m


dd($firstUser->reproductions->count()); // Should return 3 but returns null collection


千巷猫影
浏览 272回答 1
1回答

动漫人物

您可以创建两种不同的关系。public function maleReproductions(){        return $this->hasMany(Reproduction::class, 'father_id');}public function feMaleReproductions(){        return $this->hasMany(Reproduction::class, 'mother_id');}现在基于$user你可以附加关系。$productions = [];$user = User::where('id',1)->first();if($user->gender == 'm'){    $productions = $user->maleProductions;} else {    $productions = $user->feMaleProductions;}对于用户集合,附加两者的关系。并根据条件访问特定的内容。$users = User::with('maleReproductions', 'femaleReproductions')->get();foreach($users as $user){    if($user->gender == 'm'){       $productions = $user->maleProductions;    } else {       $productions = $user->feMaleProductions;    }}
随时随地看视频慕课网APP
我要回答