Laravel Eloquent:计算总价的最佳方式

时间:2015-07-15 04:42:58

标签: php laravel laravel-5 eloquent laravel-5.1

我正在用Laravel 5.1构建一个简单的买卖应用程序。每个购买模型都有许多BuyDetail,它存储购买的商品数量和buy_price。我已经在Model上实现了表之间的关系。

class Buy extends Model
{
  #Eloquent relationships

  public function supplier()
  {
    return $this->belongsTo('App\Supplier');
  }

  public function buyDetails()
  {
    return $this->hasMany('App\BuyDetail');
  }
}

我想计算每次购买的总价。使用Eloquent ORM计算总价的最佳方法是什么?

现在我只是这样实现它:

@foreach($buys as $key => $value)
    <?php
        $total = 0;
    ?>
    @foreach($value->buyDetails as $k => $bD)
        <?php
            $total += ($bD['buy_price']*$bD['qty']);
    ?>
    @endforeach

   <tr>
    <td>{{$value->ref_number}}</td>
    <td>{{$value->suplier->name}}</td>
    <td>{{$value->created_at}}</td>
    <td>{{$value->buyDetails->count()}}</td>
    <td>{{$total}}</td>
    <td>
        <a href="" class="btn btn-default btn-sm" title="show">Detail</a>
        <a href="" class="btn btn-primary btn-sm" title="edit">Edit</a>
        <a href="" class="btn btn-danger btn-sm" title="delete">Delete</a>
    </td>
  </tr>
@endforeach

0 个答案:

没有答案