首页 > 解决方案 > 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

标签: phplaravellaravel-5eloquent

解决方案


您可以创建两种不同的关系。

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

推荐阅读