在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');
}
}
}但它不会在刀片上显示任何内容。
在刀片上:
@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>
@endforeachThis is the result of dd on $products and $orderdetail
它聚合不显示刀片模板的值。如何在刀片式服务器上显示它,或者在型号或刀片式服务器上有任何问题?请帮帮忙。
发布于 2020-09-08 18:04:29
在这里,我在控制器上通过这种方式解决了问题
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'));
}在Model上,我稍微改变了一下
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') }}发布于 2020-09-02 22:29:47
如果您希望通过已定义的关系访问列的sum,则需要在主查询中添加该关系:
$products = Product::with('category', 'supplier')->with(['orderdetail' => function($query){
$query->select('id', 'product_id', 'quantity', DB::raw('sum(quantity) as sum'));
}])->get();https://stackoverflow.com/questions/63705104
复制相似问题