开发者

Calculation in beforeValidate callback based data from a HasMany relationship in cakephp

eg. Invoice hasMany LineItems

When a new invoice is created we need to sum up the LineItem totals inorder to set the Invoice total.

This can be done in afterSave callback, but would prefer to validate the totals first and avoide extra DB queries using (beforeValidate).

开发者_运维知识库How would I best achieve this?


just do in your controller

$sum = array_sum(Set::classicExtract($this->data, 'Invoice.{n}.LineItems.price'));

$sum will be the total of your Invoice. I assume the structure of $this->data to be

$this->data['Invoice']
      [0] => ['LineItems'] => ['price']

if this is not right change the path to meet your needs or edit your post to show the correct structure of $this->data

hope it helps you

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜