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

如何在Laravel中关联两张表并查询各criteria对应的总得分

Laravel 统计每个指标(Criteria)总得分实现方案

前置说明

以下示例默认你的评分关联表名为ratings,关联外键为criteria_id,得分存储字段为score,如果和你的实际表结构不一致,替换为对应字段即可。

步骤1:配置模型关联

在app/Models/Criteria.php中定义一对多关联:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Criteria extends Model
{
    protected $fillable = ['name', 'weight', 'description'];

    // 关联评分表
    public function ratings(): HasMany
    {
        return $this->hasMany(Rating::class);
    }
}

步骤2:执行统计查询

方式1:Eloquent ORM 实现(推荐)

使用Laravel内置的withSum方法快速统计,代码更简洁易维护:

// 查询逻辑
$criteriaTotalScores = Criteria::select('id', 'name')
    ->withSum('ratings', 'score')
    ->get()
    ->map(fn($item) => [
        'id' => $item->id,
        'name' => $item->name,
        'total_score' => $item->ratings_sum_score ?? 0
    ]);

方式2:查询构造器实现(性能更优)

适合数据量较大的场景,直接走SQL查询减少模型开销:

use Illuminate\Support\Facades\DB;

$criteriaTotalScores = DB::table('criteria')
    ->leftJoin('ratings', 'criteria.id', '=', 'ratings.criteria_id')
    ->select(
        'criteria.id',
        'criteria.name',
        DB::raw('COALESCE(SUM(ratings.score), 0) as total_score')
    )
    ->groupBy('criteria.id', 'criteria.name')
    ->get();

步骤3:结果渲染(按需使用)

如果需要输出为表格样式,在Blade模板中循环输出即可:

<table border="1" cellpadding="8" cellspacing="0">
    <tr>
        <th>指标ID</th>
        <th>指标名称</th>
        <th>总得分</th>
    </tr>
    @foreach($criteriaTotalScores as $criteria)
    <tr>
        <td>{{ $criteria['id'] ?? $criteria->id }}</td>
        <td>{{ $criteria['name'] ?? $criteria->name }}</td>
        <td>{{ $criteria['total_score'] ?? $criteria->total_score }}</td>
    </tr>
    @endforeach
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:30:00