Php Laravel:创建基于条件的多个关系
我需要根据性别条件显示复制品 复制表:Php Laravel:创建基于条件的多个关系,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我需要根据性别条件显示复制品 复制表: $table->bigIncrements('id'); $table->unsignedInteger('father_id'); $table->unsignedInteger('mother_id'); ... id father_id mother_id 1 1 2 2 1 3 3 1 4 我需要
$table->bigIncrements('id');
$table->unsignedInteger('father_id');
$table->unsignedInteger('mother_id');
...
id father_id mother_id
1 1 2
2 1 3
3 1 4
我需要根据性别检索复制品
User.php
public function reproductions(){
if($this->gender == 'm'){
return $this->hasMany(Reproduction::class, 'father_id');
}else{
return $this->hasMany(Reproduction::class, 'mother_id');
}
}
复制表:
$table->bigIncrements('id');
$table->unsignedInteger('father_id');
$table->unsignedInteger('mother_id');
...
id father_id mother_id
1 1 2
2 1 3
3 1 4
当我为id为1的用户检索复制时,它需要显示3个复制,但它返回空集合
$firstUser = User::find(1); // User Id with 1 has gender m
dd($firstUser->reproductions->count()); // Should return 3 but returns null collection
您可以创建两种不同的关系
public function maleReproductions(){
return $this->hasMany(Reproduction::class, 'father_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;
}
}
您可以创建两种不同的关系
public function maleReproductions(){
return $this->hasMany(Reproduction::class, 'father_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;
}
}
非常感谢。对于我所做的收集,
User::with('maleproductions','femaleproductions')代码>用于eagar加载,并基于单个集合项访问循环中的特定关系,对吗?您介意编辑我的答案或给我代码,以便我可以自己编辑。是的,与您添加的条件相同。我已经编辑了我的答案,如果答案错误,请更正。谢谢。对于我所做的收集,User::with('maleproductions','femaleproductions')代码>用于eagar加载,并基于单个集合项访问循环中的特定关系,对吗?您是否介意编辑我的答案或给我代码,以便我可以自己编辑。是的,与您添加的条件相同。我已编辑了我的答案,如果错误,请更正。为什么不在性别和用户之间创建一个piviot表。从这一点来说,id是什么并不重要。你可以一直过滤,然后做一个cout。不用创建两个不同的关系等等。为什么不在用户之间创建一个piviot表呢。从这一点来说,id是什么并不重要。你可以一直过滤,然后做一个cout。避免您创建两个不同的关系等。