开发者

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

开发者 https://www.devze.com 2023-04-06 01:00 出处:网络
eg. Invoice hasMany LineItems When a new invoice is created we need to sum up the LineItem totals inorder to set the Invoice total.

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

精彩评论

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