2016-10-04 35 views
1

我想在cakephp 3.2中总结一个字段。 但是该领域存在于hasOne模型协会。如何使用cakephp 3.2内置总和功能在不在父表中的关联表中求和操作(求和字段)?

我想在绑定查询中执行此操作。

我有一个订单表,我正在模型绑定与集合表。

在这里,我想总结一下所有的due_amount在集合表

我都试过,但它不工作。

请检查我的代码,是否有任何错误。

$this->Orders->hasOne('Collections', [ 
       'className' => 'Collections', 
       'foreignKey' => 'order_id', 
       'strategy' => 'select', 
       'conditions' => function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) { 
        $query->order(['Collections.id' => 'ASC']); 
        return []; 
       } 
        ]); 
      $get_total_sales = $this->Orders->find('all')->where($condition)->select(['id', 'region_id', 'net_total'])->contain(['Collections' => ['queryBuilder' => function ($q) { 
           return $q->select(['id', 'order_id', 'total_sale_amount', 'due_amount']); 
          }]])->order(['Orders.due_date DESC']); 


$res2 = $get_total_sales->select(['total_due' =>$get_total_sales->func()->sum('collection.due_amount')])->first(); 

echo $due = $res2->total_due;//its showing column not find error. 
Is it working in order table instead of collections table? 
How can i do it for collection table using the $get_total_sales listing results? 



Below some out put 

[ 
    { 
     "id": 40, 
     "region_id": 2, 
     "net_total": 2899.12, 
     "collection": { 
      "id": 182, 
      "order_id": 40, 
      "total_sale_amount": 2899.12, 
      "due_amount": 1990 
     }, 

    }, 
    { 
     "id": 38, 
     "region_id": 2, 
     "net_total": 110, 
     "collection": { 
      "id": 181, 
      "order_id": 38, 
      "total_sale_amount": 110, 
      "due_amount": 10 
     }, 

    }, 
    { 
     "id": 39, 
     "region_id": 2, 
     "net_total": 16670, 
     "collection": { 
      "id": 190, 
      "order_id": 39, 
      "total_sale_amount": 16670, 
      "due_amount": 16630.99 
     }, 

    }, 

在这里,我想总结一下所有的due_amount在集合表

谢谢

+0

请问你可以共享db模式以及这两个表,也有一个疑问,如果它存在hasOne关系,那么显然你总是只有一个结果相关的表格,那么为什么你需要这个总和,请更好地解释这个情况以及你想要的结果。 –

+0

@Rohit Ailani其实一个记录有可能收集,但我需要最后一个。 所以我做了它,并获得所需的数据。 但我想总结所有的记录,这里总结将在子表中完成。 – sradha

+0

@Rohit Ailani我有一个表,一个是订单,一个订单有多个集合 – sradha

回答

1

您可以使用子表,而你的情况是收藏表的虚拟领域。

您可以查看文档中cakephp3 here

创建虚拟域和虚拟领域,你可以指定SUM函数。要写和数函数,你可以参考here

+0

谢谢...... :) :) – sradha

+0

是的虚拟场是一种方式,我发现了一些不使用vf的方式。 所以谢谢:) – sradha

+0

请分享其他方式,如果有其他人需要,他们可以同时访问。 –

相关问题