为什么$ total显示40,而不显示20?

时间:2018-07-04 16:57:58

标签: laravel

一个会议中有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

我想获得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
              ]
            }
          ]
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

假设您在hasManyRegistration之间具有Participant关系,请尝试一次。同样,ParticipantbelongsTo具有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