Laravel+Inertia+Vuejs中两张关联表统计各部门用户数量的实现问题
问题核心原因
- 你写的
User::where('department_id')->count()没有传where条件的匹配值,实际是统计全表用户总数,而且你把total_members定义成了全局单一值,不是每个部门对应的独立统计值,自然没法在遍历部门时拿到对应数据。 - 你把
dd()写在了Inertia渲染的参数数组里,代码执行到这直接终止,页面根本无法正常渲染。
调整步骤
1. 先配置模型关联
确保app/Models/Department.php已经定义和用户表的一对多关联,添加如下代码:
public function users() { return $this->hasMany(User::class); }
2. 修改Controller代码
用Laravel自带的withCount方法,查询部门的时候直接预加载每个部门的用户统计值,同时删掉错误的全局统计和dd语句,修改后的DepartmentController.php代码:
public function index() { return Inertia::render('back/app/departments/index', [ 'filters' => request()->all('visibility', 'status', 'search'), // withCount会自动给每个department对象新增users_count属性,值为对应部门的用户数 // 如果要自定义属性名可以写成 withCount(['users as total_members']) 'departments' => Department::withCount('users')->orderBy('name')->get(), ]); }
3. 修改Vue前端代码
如果用默认的users_count属性,把前端对应的取值字段修改即可:
<td class="flex items-center text-sm leading-5 text-gray-500 px-6 py-4 whitespace-no-wrap"> <span class="font-medium">{{ department.users_count }}</span> {{ $trans('labels.members') }} </td> <td class="px-6 py-4 whitespace-no-wrap text-right text-sm leading-5 font-medium"> <inertia-link :href="route('app:projectdepartment.index', {id: department.id})"> {{ $trans('labels.view-activity') }} </inertia-link> </td>
如果Controller里用了withCount(['users as total_members'])自定义属性名,前端代码不需要调整。
内容的提问来源于stack exchange,提问作者valdimiro einstein
相关产品推荐
相关产品推荐

