Laravel:基于条件创建HasMany关系

编程入门 行业动态 更新时间:2024-10-18 16:51:44
本文介绍了Laravel:基于条件创建HasMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要根据性别状况显示复制品

I need to display reproductions based on Gender Condition

复制表:

$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'); } }

复制表:

id father_id mother_id 1 1 2 2 1 3 3 1 4

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

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

推荐答案

,您可以创建两个不同的关系.

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'); }

现在基于 $ user ,您可以附加关系.

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; } }

更多推荐

Laravel:基于条件创建HasMany关系

本文发布于:2023-10-24 20:13:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524890.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   关系   Laravel   HasMany

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!