php - 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
解决方案
您可以创建两种不同的关系。
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;
}
}
推荐阅读
- android - 未收到 Firebase 异步消息
- powershell - Powershell 网络会话
- node.js - Webpack“npm run build”在谷歌云上不起作用,但在本地机器上工作
- javascript - 在递归函数中通过引用传递
- javascript - 切换/暂停 JavaScript 滚动功能
- hbase - HBase convertScanToString 方法不接受 scan.write
- python-3.x - round() 函数在 apply() 函数中的行为不同
- visual-studio-code - 如何从扩展程序触发 VSCode 中的系统铃声?
- javascript - 为什么我的带有 setTimeout 函数的 requestAnimation 在 Chrome/Opera 中不起作用?
- excel - 如何将 COUNTIFS 与 INDIRECT 结合使用?