簡體   English   中英

Laravel Eloquent - 嵌套關系中的數組,如何分配?

[英]Laravel Eloquent - Array in a Nested Relation, how to assign it?

我有一個游戲數據庫,其中一場比賽有兩支球隊(team_home_id 和 team_away_id)。 用戶可以對這些游戲進行預測。

所以 model 匹配有這個:

public function teamHome()
{
    return $this->belongsTo(Team::class, 'team_home_id');
}

public function teamAway()
{
    return $this->belongsTo(Team::class, 'team_away_id');
}

我想從特定用戶那里獲得這場比賽的所有預測。 預測 model 有一個多態表(因為有比賽的預測和整個賽季的預測)。

在 controller 我這樣做:

        $matches = Match::where('match_day', $match_day)->with('teamHome', 'teamAway', 'predictions')->get();

foreach ($matches as $match) {

    echo $match->teamHome->code . '-';
    echo $match->teamAway->code . '  ';
   // echoing is just for testing purpose
    //dd($match->predictions); // this is the problem, what is the best way?
}

我得到了一個數組,其中包含我無法分配給特定用戶或只能使用手動 foreach 並將其分配給不同數組的預測。 但我認為這不是一個好方法。

我該如何解決這個問題?

提前致謝。

有幾種方法可以解決您的問題。 這只是其中之一:

您可以使用約束急切加載,即“僅帶來來自用戶 X 的預測”。

$matches = Match::where('match_day', $match_day)
   ->with('teamHome', 'teamAway')
   ->with(['predictions' => function($prediction) use($userId){
      $prediction->where('user_id', '=', $userId);
   }])
   ->get();

資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM