Laravel收集总和与数据透视表的字段

时间:2017-03-17 16:42:02

标签: php mysql laravel eloquent

这是我的数据库表:

**orders:**
id, customer_id, date .....etc

**packagings**
id, code, name .....

**products**
id, code, name, weight .......

带有数据透视表的2个多表:

**packaging_product:**
packaging_id, product_id, quantity

**packaging_order:**
packaging_id, order_id, quantity

要获得一个订单的总重量,我的订单模型中包含此属性:

public function getWeightAttribute()
{
    $tot_weight = 0;
    foreach ($this->packagings as $pack) {
        $tot_weight += $pack->weight * $pack->original['pivot_quantity'];
    }
    return $tot_weight; 
}

我从这个包装模型的属性获得包装重量:

public function getWeightAttribute()
{
    return $this->products()->sum(DB::raw('products.weight * quantity'));
}

使用eloquance集合是否有更优雅的方法?

0 个答案:

没有答案