我有三张桌子:需求,产品和接收。为了链接需求和接收,我对接收表使用以下模式,而不是透视表(即demand_receive)。让receives表的实例如下所示。

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

透视表需求产品如下所示。
 |**demand_id** |**product_id** |**demand_quantity** |
 |D2            |P1             |100                 |
 |D2            |P2             |500                 |
 |D2            |P3             |1000                |

为了跟踪需求的接收产品,我制作了如下所示的pivot table product_receive。
 |**receive_id** |**product_id** |**receive_quantity** |
 |R1             |P1             |50                   |
 |R2             |P1             |40                   |
 |R2             |P2             |500                  |

在这里,我试图追踪部分需求的接收。我真正想要的是找到给定需求id的单个产品的总接收数量,以便结果可以用于控制视图中的接收数量(即总接收数量)。
例如:
for demand id D2,
total_receive_quantity of P1=90
total_receive_quantity of P2=500
total_receive_quantity of P3=0

我怎样才能在拉勒维尔得到上述答案?
提前谢谢。

最佳答案

应该可以这样做:

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');
    }
}

09-30 22:32