Nishal Gurung
Nishal Gurung

Reputation: 481

Calculating sum in pivot table in 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.

Upvotes: 3

Views: 390

Answers (1)

WebSpanner
WebSpanner

Reputation: 424

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

Upvotes: -1

Related Questions