This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

huynhnam061332049
huynhnam061332049

I used RelationBehavior to get some pivot data, and I want to calculate two columns of that pivot data. So how can I do it. Example: Three columns below are pivot: Product price Discount Sell price = Product price * discount

mjauvin
mjauvin

What do you want to know exactly?

huynhnam061332049
huynhnam061332049

Can I calculate value between columns of pivot data? Ex: Sum of two columns, ....

mjauvin
mjauvin

Yes, see this docs page https://octobercms.com/docs/database/relations#many-to-many

under the "Retrieving intermediate table columns" section.

You can define an accessor method to calculate the sum.

mjauvin
mjauvin
mjauvin

Just to be sure, do you want the sum as a column in the records list view or as a field in the record create/update form?

huynhnam061332049
huynhnam061332049

I want to sum columns in Form, but Form in Relation popup. In normal model, I used dependsOn and filterFields to update a fields from another field, so can I do that in Relation popup? I tried filterFields in pivot model but don't work

mjauvin
mjauvin

I see. Show some code so I can assist.

huynhnam061332049
huynhnam061332049
pivot[based_price]:
              label: Giá bán lẻ
              type: number
              defaultFrom: price
              readOnly: true

pivot[discount]:
              label: Chiết khấu (%)
              type: number
              span: auto
              default: 0

pivot[quantity]:
              label: Số lượng
              type: number
              span: auto
              default: 1
              min: 1

pivot[sell_price]:
              label: Giá bán
              type: number
              defaultFrom: 

pivot[based_price] *  pivot[discount]
              hidden: 1
              dependsOn:
                - pivot[discount]

I want sell_price will be calculate from based_price and discount (based_price is fixed and discount is filled by user)

Last updated

mjauvin
mjauvin

Maybe use this to manipulate the pivot widget would work:

https://octobercms.com/docs/backend/relations#extend-pivot-widget

huynhnam061332049
huynhnam061332049

class OrderProductPivot extends Pivot {

public function setSellPriceAttribute()
{
    $this->attributes['sell_price'] = $this->based_price *  ( (100 - $this->discount) / 100) ;
}

}

Hi @mjauvin, thanks for your supporting. I have tried to use set attribute function inside pivot model and set dependsOn in pivot form. And it works according to my expectations

Last updated

mjauvin

1-12 of 12

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.