laravel - Laravel Aggregates 查询无法根据 group by
问题描述
在 POS 上,当我下任何订单时,它会根据 order_details 表中的产品 ID 存储订单详细信息。我想根据产品 ID 对数量订单求和。订单明细表:id、order_id、product_id、total、created_at、updated_at
产品控制器:
public function index()
{
$orderdetail = DB::table('order_details')
->select('quantity', DB::raw('sum(quantity) as sum'))
->groupBy('product_id')
->havingRaw('SUM(quantity)')
->get();
$products = Product::latest()->with('category', 'supplier', 'orderdetail')->get();
return view('admin.product.index', compact('products', 'orderdetail'));
}
关于产品型号:
class Product extends Model
{
protected $dates = [
'buying_date', 'expire_date',
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function supplier()
{
return $this->belongsTo(Supplier::class);
}
public function orderdetail()
{
return $this->belongsTo('App\OrderDetail', 'id', 'product_id');
}
}
}
但它没有在 Blade 上显示任何内容。
在刀片上:
@foreach($products as $key => $product)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ $product->name }}</td>
<td>
<img class="img-rounded" style="height:35px; width: 35px;" src="{{ URL::asset("storage/product/".$product->image) }}" alt="{{ $product->name }}">
</td>
<td>{{ $product->category->name }}</td>
<td>{{ $product->supplier->name }}</td>
<td>{{ $product->code }}</td>
<td>{{ $product->buying_date->toFormattedDateString() }}</td>
<td>{{ number_format($product->buying_price, 2) }}</td>
<td>{{ number_format($product->selling_price, 2) }}</td>
<td>{{ $product->product_unit }}</td>
<td>{{ $product->product_unit - $product->sum }}</td>
<td>{{ $product->sum }}</td>
<td>DLT</td>
</tr>
@endforeach
这是dd
$products 和 $orderdetail的结果
它聚合不显示刀片模板的值。我如何在刀片上显示它或模型或刀片上有任何问题?请帮忙。
解决方案
在这里,我通过这种方式在Controller上解决了
public function index()
{
$orderdetail = DB::table('order_details')
->select('quantity', DB::raw('sum(quantity) as soldunit'))
->groupBy('product_id')
->get();
$products = Product::latest()->with('category', 'supplier', 'orderdetail')->get();
return view('admin.product.index', compact('products', 'orderdetail'));
}
在模型上,我略有改变
public function orderdetail()
{
return $this->hasMany('App\OrderDetail','product_id', 'id')->selectRaw('order_details.*,sum(quantity) as soldunit')->groupBy('product_id');
}
在此之后,为了访问刀片上的 soldunit,我使用了这个
{{ $product->orderdetail->sum('soldunit') }}
推荐阅读
- c# - 游戏世界中从相机到鼠标位置的光线投射
- javascript - Node.js:杂耍异步(learnyounode)。回调函数中的递归未按预期工作
- cordova - 离子 - 离子发球后出现白屏
- fortran - 在 fortran 程序中运行 mpi 子例程
- python - ImportError:无法导入名称“x”
- angular - 在调用方法之前等待数组使用来自 Firebase 的数据进行初始化
- typescript - rxjs 5.5 管道 fs readdir 事件
- serial-port - 可靠地扫描多个串行数据位 - 8051
- python-3.x - 从解析的 html 页面中查找推文 ID
- angularjs - ng-repeat 不读取 SQL json 文件结果