首页 > 解决方案 > 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的结果

它聚合不显示刀片模板的值。我如何在刀片上显示它或模型或刀片上有任何问题?请帮忙。

标签: laravel

解决方案


在这里,我通过这种方式在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') }}

推荐阅读