我有3个表:需求,产品和接收。为了链接需求和接收,我使用接收表而不是数据透视表(即demand_receive)的以下模式。让接收表的实例如下所示。
|**id** | **demand_id** | **receive_note** | **receive_date** |
|R1 |D2 | |10/29/2015 |
|R2 |D2 | |10/30/2015 |
数据透视表 demand_product 如下所示。
|**demand_id** |**product_id** |**demand_quantity** |
|D2 |P1 |100 |
|D2 |P2 |500 |
|D2 |P3 |1000 |
为追踪需求的接收产品,我制作了数据透视表 product_receive ,如下所示。
|**receive_id** |**product_id** |**receive_quantity** |
|R1 |P1 |50 |
|R2 |P1 |40 |
|R2 |P2 |500 |
在这里,我试图追踪部分接收需求。我真正想要的是找到给定需求ID的单个产品的总接收数量,以便结果可用于控制视图中的接收数量(例如total_received_quantity)。
例如:
for demand id D2,
total_receive_quantity of P1=90
total_receive_quantity of P2=500
total_receive_quantity of P3=0
如何在laravel中获得以上答案? 提前谢谢。
答案 0 :(得分:-1)
应该可以这样做:
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');
}
}