我是 Laravel 的新手,而且特別雄辯。我有一個 Match 模型,這個 match 有目標
class Match extends Model
{
use HasFactory;
public function goals()
{
return $this->hasMany(Goal::class, 'match');
}
}
我是這樣從 Controller 呼叫它的:
public function matchesWithGoals()
{
$matches = Match::with('goals')->get();
return compact('matches');
}
這將回傳每場比賽及其自己的目標集合。到目前為止一切都很好。
{
"matches": [
{
"id": 13,
"date": "2022-01-05",
"goals": [
{
"id": 2,
"player": 4,
"match": 13,
"team": "b"
},
{
"id": 3,
"player": 13,
"match": 13,
"team": "b"
},
{
"id": 4,
"player": 4,
"match": 13,
"team": "a"
}]
}]}
我想做的是獲取每個嵌套的目標集合,根據團隊加起來,并附加自定義屬性“goalsTeamA”、“goalsTeamB”、“matchResult”。
我試著分開做這件事,得到所有的比賽,得到所有的目標,然后加入他們。但似乎應該有一種直接的方法來計算嵌套集合中的元素基于屬性,在這種情況下是團隊,并附加屬性,因此預期的結果將是這樣的:
{
"matches": [
{
"id": 13,
"date": "2022-01-05"
"goalsTeamA": 1,
"goalsTeamB": 2,
"Result": "b"
},
{
"id": 14,
"date": "2022-01-12"
"goalsTeamA": 3,
"goalsTeamB": 7,
"Result": "b"
}]
}
我怎樣才能做到這一點?
BTW, the reason I'm trying to do it this way instead of just adding this columns to the DB with the scores is because I'm not just only be displaying scores counting up. Matches have other relationships like roster, and my goal is to learn how to process those nested relationship collections and append those results as attributes. Summing up the golas seemed like the most basic scenario.
uj5u.com熱心網友回復:
有幾種方法可以做到這一點,所以我將提供一種可能的解決方案。
您可以查看 Laravel 訪問器 - https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor
在您的情況下,您可以在 Match 模型上具有如下功能:
public function getGoalsTeamAAttribute() {
// calculate and return goal count for team A
}
public function getGoalsTeamBAttribute() {
// calculate and return goal count for team B
}
public function getResultAttribute() {
// calculate and return result
}
然后,您可以執行以下兩項操作之一以將此資料包含在集合中。
添加
$appends = ['result', 'goals_team_a', 'goals_team_b'];到匹配模型的頂部。當您將其轉換為陣列或 JSON 時,這會將這些值附加到集合中。谷歌“laravel 附加”以獲取更多資訊。當您將 Match 作為 eloquent 物件時,只需呼叫
$match->goals_team_a它,它就會即時進行計算。您需要小心這種方法的 n 1 問題,因為它會運行您的getGoalsTeamAAttribute函式中的任何資料庫查詢。您需要確保->with('goals')在運行之前延遲加載 ()$match->goals_team_a。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416423.html
標籤:
上一篇:如何使用碳選擇格式日期?
