首页 > 解决方案 > Laravel:如何进行数学计算

问题描述

在产品表中我有一个销售价格列和一个购买价格列,我如何从每个项目中获取利润并将其显示在 Blade.php

标签: laravellaravel-5

解决方案


解决方案1:

// ProductController
public function index() {
  return view('products')->with(['products' => Product::all()]);
}

// products.blade.php
@foreach($products as $product)
Profit: {{ $product->purchase_price - $product->selling_price }}
@endforeach

解决方案 2

// ProductController
public function index() {
  return view('products')->with(['products' => Product::all()]);
}

// Product.php
public function getProfitAttribute(){
  return $this->purchase_price - $this->selling_price;
}
protected $appends = ['profit']; // to append to json

// products.blade.php
@foreach($products as $product)
Profit: {{ $product->profit }}
@endforeach

解决方案3(这里最好最快)


// ProductController
public function index() {
  return view('products')->with(['products' => Product::all(['*', DB::raw('purchase_price - selling_price as profit')])]);
}

// products.blade.php
@foreach($products as $product)
Profit: {{ $product->profit }}
@endforeach

推荐阅读