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

Laravel 8 hasManyThrough关联查询结果的applications数组计数方法

Laravel 统计关联applications数组元素数量的方法

方法1:基于现有代码直接统计(需要用到applications明细数据时用)

你当前的代码中get()返回的是包含单条StaffRole的集合,建议优先用first()直接获取单条模型实例,统计写法如下:

Route::get('/admin/applications/staff-role', function () {
    // 查询单条指定ID的StaffRole,预加载关联的applications
    $staff = StaffRole::with('applications')->where('id', '=', '1')->first();
    // 直接对关联集合调用count方法获取总数
    $applicationTotal = $staff->applications->count();
    
    // 可以根据需要返回数据,示例同时返回角色信息和统计数
    return [
        'staff_role_info' => $staff,
        'application_total' => $applicationTotal
    ];
});

方法2:高效统计(仅需要总数不需要applications明细时用)

如果不需要获取applications的具体数据,推荐使用Laravel自带的withCount方法,无需查询关联表的全量字段,性能更高:

Route::get('/admin/applications/staff-role', function () {
    // withCount会自动生成applications_count属性存储关联数量
    $staff = StaffRole::withCount('applications')->where('id', '=', '1')->first();
    
    return [
        'staff_role_info' => $staff,
        'application_total' => $staff->applications_count
    ];
});

前端统计方案

如果你直接使用你贴出的原有接口返回结果,只需要在前端取对应数组的长度即可,以JS为例:

// 假设接口返回的数据存在res变量中
const applicationTotal = res[0].applications.length;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:18:05