z3r0
z3r0

Reputation: 139

Sum array of Object Relationship in Laravel Using Vuejs

I'm trying to Sum Array amount of Laravel Relationship Using Vuejs using computed.

enter image description here

By the Way its Return NaN Result....

   computed: {
        subTotal() {
            return this.items.reduce((total, item) => {
                return total + parseFloat(item.deposits.amount);
            }, 0);
        }
    },

Thanks.....

Upvotes: 1

Views: 437

Answers (2)

Lim Socheat
Lim Socheat

Reputation: 715

  1. Do sum relationship in Laravel

    protected $appends = ['deposit_amount'];

    public function getDepositAmountAttribute(){ return $this->deposits()->sum('amount'); }

  2. VueJS Computed Property

    computed: { deposit_amount() { var amount = 0; for(let i = 0; i < this.item.deposits.length; i++) { amount += parseFloat(this.item.deposits[i].amount); } return amount; } }

Upvotes: 0

Riddhi
Riddhi

Reputation: 2244

The below code will return an array of sum for all items within the array index wise.

computed: {
    subTotal() {
        let itemsum = []
        this.items.forEach(item => {
            if (item.deposits && item.deposits.length > 0) {
                let total_deposit = item.deposits.reduce((total, val) => {
                    return  parseFloat(total.amount) + parseFloat(val.amount);
                }, 0);
                itemsum.push(total_deposit);
            } else {
                itemsum.push(0);
            }                  
        })
        return itemsum
    }
},

Upvotes: 1

Related Questions