doujiu8479 2015-10-30 11:11
浏览 141

在laravel 5中计算数据透视表中的总和

I have 3 tables: demands,products and receives. To link demands and receives, I am using following schema for receives table instead of pivot table (i.e demand_receive). Let the instance of receives table looks like below.

|**id** | **demand_id** | **receive_note** | **receive_date** |
|R1     |D2             |                  |10/29/2015        |
|R2     |D2             |                  |10/30/2015        |

pivot table demand_product looks like below.

 |**demand_id** |**product_id** |**demand_quantity** |
 |D2            |P1             |100                 |
 |D2            |P2             |500                 |
 |D2            |P3             |1000                |

To trace the receiving products of the demand, I have made pivot table product_receive which looks like below.

 |**receive_id** |**product_id** |**receive_quantity** |
 |R1             |P1             |50                   |
 |R2             |P1             |40                   |
 |R2             |P2             |500                  |

Here, I am trying to trace partial receive of demand. What I actually want is to find the total receive quantity of an individual product of a given demand id so that the result can be used to control receive quantity(say total_received_quantity) in the views.

For example:

for demand id D2, 
total_receive_quantity of P1=90
total_receive_quantity of P2=500
total_receive_quantity of P3=0

How can I achieve above answer in laravel? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douxian9060 2015-11-02 00:51
    关注

    It should be possible to do this like so:

    class Demand extends Model
    {
        public function receives() {
            return $this->hasMany('App\Receive')
        }
    
        public function total_received_quantity($product_id) {
            $tally = 0;
            $receives = $this->receives;
            foreach ($receives as $receive) {
                $product_receives = $receive->product_receives;
                foreach ($product_receives as $product_receive) {
                     if ($product_receive->product->id == $product_id){
                         $tally = $tally + $product_receive->product->quantity;
                    }
                }
            }
            return $tally;
        }
    }
    
    class Receive extends Model
    {
        public function product_receives() {
            return $this->hasMany('App/Product_receive');
        } 
    }
    
    class Product_receive extends Model
    {
        public function product() {
            return $this->belongsTo('App\Product');
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度