亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel:根據條件創建 HasMany 關系

Laravel:根據條件創建 HasMany 關系

PHP
千巷貓影 2022-11-12 13:42:55
我需要根據性別條件顯示復制品再現表:$table->bigIncrements('id');$table->unsignedInteger('father_id');$table->unsignedInteger('mother_id');...我需要根據性別檢索復制品用戶.phppublic 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_id1         1            22         1            33         1            4當我檢索 ID 為 1 的用戶的復制品時,它需要顯示 3 個復制品,但它返回 null 集合$firstUser = User::find(1); // User Id with 1 has gender mdd($firstUser->reproductions->count()); // Should return 3 but returns null collection
查看完整描述

1 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

您可以創建兩種不同的關系。


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;

    }

}


查看完整回答
反對 回復 2022-11-12
  • 1 回答
  • 0 關注
  • 299 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號