会議には2人の参加者が1人登録されているので、データベースは以下のようになります。
登録表
id conference_id user_that_did_registration
1 1 1
参加者テーブル
id registration_id registration_type_id
4 4 1
5 4 1
登録タイプテーブル
id name conference_id price
1 general 1 10
価格が10の登録タイプ「1」に関連付けられた参加者がそれぞれ2人いるため、ID「1」の登録の合計価格を20にする必要があります。
私はこのコードを持っていますが、dd($ total)は20ではなく40を示しています。理由を知っていますか?
$registrationTypeDetails = Registration::with(['participants.registration_type',
'participants' => function ($query) use ($regID) {
$query->select('id', 'registration_type_id', 'registration_id')->where('registration_id', $regID);
}
])->find($regID);
if ($registrationTypeDetails->user_that_did_registration != $user_id) {
return redirect('/');
} else {
$total = 0;
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
dd($registrationTypeDetails->participants);
foreach ($registrationTypeDetails->participants as $participant) {
$total += $participant->registration_type->price * $type_counts[$name];
}
dd($total); // shows 40 not 20
}
$ registrationTypeDetailsは次のことを示しています。
Registration {#290 ▼
#relations: array:1 [▼
"participants" => Collection {#299 ▼
#items: array:2 [▼
0 => Participant {#306 ▼
#relations: array:1 [▼
"registration_type" => RegistrationType {#311 ▶}
]
}
1 => Participant {#308 ▼
#relations: array:1 [▼
"registration_type" => RegistrationType {#311 ▼
#attributes: array:11 [▼
"id" => 1
"name" => "general"
"price" => 10
"conference_id" => 1
]
}
]
}
]
}
]
}
あなたが持っていると仮定すると、この一回を試してみてくださいhasMany
との関係Registration
とをParticipant
。同様Participant
にbelongsTo
と関係がありますRegistrationType
$registration = Registration::with('participants', 'participants.registration_type')->find($regID);
$totalPrice = $registration->participants->sum(function ($participant) {
return $participant->registration_type->price;
});
echo $totalPrice;
Laravelコレクションの合計https://laravel.com/docs/5.6/collections#method-sum
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加