laravel - Laravel:如何进行数学计算
问题描述
在产品表中我有一个销售价格列和一个购买价格列,我如何从每个项目中获取利润并将其显示在 Blade.php
解决方案
解决方案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
推荐阅读
- javascript - 如何在客户端从服务器获取数据期间创建屏幕保护程序?
- java - JVM 是否会在分布式/并行处理中产生大量开销?
- javascript - 如何更改 ng-zorro 中进度圈的笔触颜色?
- android - 我如何在一个活动中使用多个 XML 布局而不必创建这么多活动
- azure - 具有对象 id 的客户端无权执行操作 taggedTrafficConsumers/validate
- php - 在 Ubuntu 18.04 crontab 中执行 PHP
- javascript - 使用 create-react-app 结构时进行更新道具 onChange 的输入?
- docker - 如何在由父 docker 共享 docker.sock 创建的子 docker 内挂载卷
- python - 检查 4D 图中缺失的坐标组合并为缺失的组合添加虚拟值
- swift - 如何识别 SKCamera 视图中的特定节点?