0

一个会议有 1 个注册,有 2 个参与者,所以数据库如下所示。

登记表

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

我想获得 ID 为“1”的注册总价格应该是 20,因为有 2 个参与者,每个参与者都与价格为 10 的注册类型“1”相关联。

我有这段代码,但 dd($total) 显示的是 40 而不是 20。你知道为什么吗?

$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
              ]
            }
          ]
        }
      ]
    }
  ]
}
4

1 回答 1

0

假设您在和之间有hasMany关系,请尝试一次。同样有关系RegistrationParticipantParticipantbelongsToRegistrationType

$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

于 2018-07-04T17:30:32.690 回答