You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel关联表数据展示:如何显示品牌对应交易订单数量

解决方案

你当前的查询通过join关联后直接get(),会返回每条已接受交易对应的品牌数据,所以品牌名称会重复出现交易次数。要实现每个品牌显示一次并附带已接受交易数量,可通过以下两种方式修改:

方法一:使用Laravel关联计数(推荐)

这种方式更符合Laravel的ORM设计,需要先在Brands模型中定义与Trades的关联关系:

步骤1:定义模型关联

在App\Models\Brands(根据你的实际模型路径调整)中添加关联方法:

public function trades()
{
    return $this->hasMany(\App\Models\Trades::class, 'brandid');
}

步骤2:修改控制器查询

利用withCount方法直接统计每个品牌的已接受交易数量:

public function brandorders(){
    $countorders = Brands::where('status', 'active')
        ->withCount(['trades' => function($query) {
            // 过滤出状态为accepted的交易
            $query->where('status', 'accepted');
        }])
        ->get();
    
    return view('manage.brandorders', compact('countorders'));
}

步骤3:修改Blade视图

直接调用统计字段trades_count展示数量:

@foreach ($countorders as $countorder)
    <p>{{ $countorder->brand_name }}:已接受交易 {{ $countorder->trades_count }} 条</p>
@endforeach

方法二:使用Join+分组统计

如果不想定义模型关联,可通过原生SQL分组统计实现:

步骤1:修改控制器查询

通过selectRaw和groupBy分组计算每个品牌的交易数量:

use Illuminate\Support\Facades\DB;

public function brandorders(){
    $countorders = Brands::select('brands.id', 'brands.brand_name', DB::raw('COUNT(trades.id) as accepted_trade_count'))
        ->where('brands.status', 'active')
        ->join('trades', 'trades.brandid', '=', 'brands.id')
        ->where('trades.status', '=', 'accepted')
        ->groupBy('brands.id', 'brands.brand_name')
        ->get();
    
    return view('manage.brandorders', compact('countorders'));
}

步骤2:修改Blade视图

调用自定义的统计字段accepted_trade_count:

@foreach ($countorders as $countorder)
    <p>{{ $countorder->brand_name }}:已接受交易 {{ $countorder->accepted_trade_count }} 条</p>
@endforeach

内容的提问来源于stack exchange,提问作者iCodeCrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 04:48:16