Laravel如何获取由同部门员工添加的所有客户
Laravel 查询同部门员工添加的客户
使用DB门面的JOIN写法
先获取当前登录员工的部门ID,再通过JOIN关联两张表筛选数据:
// 获取当前登录员工的部门ID $currentDepartmentId = auth()->user()->department_id; // 构建JOIN查询 $clients = DB::table('clients') ->join('employees', 'clients.created_by_employee', '=', 'employees.id') ->where('employees.department_id', $currentDepartmentId) ->select('clients.*') // 按需选择字段,可添加员工表字段如employees.name ->get();
逻辑说明:通过created_by_employee字段关联客户表和员工表,筛选出员工部门ID与当前用户一致的所有客户,自然包含当前用户自己添加的客户。
使用Eloquent关联的写法(更符合Laravel风格)
先在Client模型中定义与员工的关联:
// app/Models/Client.php public function creator() { return $this->belongsTo(Employee::class, 'created_by_employee'); }
然后通过whereHas筛选符合条件的客户:
$currentDepartmentId = auth()->user()->department_id; $clients = Client::whereHas('creator', function ($query) use ($currentDepartmentId) { $query->where('department_id', $currentDepartmentId); })->get();
注意事项
- 确保
auth()->user()返回的是Employee模型实例,需在config/auth.php中正确配置认证守卫和用户提供者。 - 若需要额外字段,可在
select方法中添加,比如select('clients.*', 'employees.name as creator_name')。
内容的提问来源于stack exchange,提问作者scully09
相关产品推荐
相关产品推荐

