elCinturon's avatar

Sum calculated field of One To Many Relationship Model

Hey,

I got 3 Models. They are called Portfolio, PortfolioEntry and PortfolieEntryValue. Portfolio got a hasMany Relation to PortfolioEntry and PortfolioEntry got a hasMany Relation to PortfolioEntryValue. Additionally to the table columns, PortfolioEntry got a calculated field latestValue which gets the latest corresponding PortfolioEntryValue.

Now I would like to add in my GET-Controller for one Portfolio the sum of alle PortfolioEntryValues corresponding to a Portfolio.

Is this possible to do only with Eloquen Queries? For example with sum? I couldn't manage to do this in the desired way. I did the following but I am not satisfied. In the Portfolio-Model I placed the following Attribute function:

protected function getTotalValueAttribute(): int
{
        $entries = $this->portfolioEntries()->with('latestValue')->get();

        $sum = 0;
        foreach ($entries as $entrie) {
            $sum += $entrie->latestValue->value;
        }
        return $sum;
    }

All my tries to solve it shorter resulted in errors.

0 likes
1 reply
PovilasKorop's avatar
Level 11

I would shorten it to use Collections instead of foreach.

Not sure if this would work, try:

protected function getTotalValueAttribute(): int
{
    return $this->portfolioEntries()->with('latestValue')->get()->sum('latestValue.value');
}

Please or to participate in this conversation.