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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:42:14