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

Laravel如何用Eloquent获取与指定分组未关联的部门数据

使用Eloquent关联获取未关联指定分组的部门记录

当然可以用 Eloquent 实现这个需求!而且通过合理定义关联,代码会比原生SQL更简洁易读。我来一步步给你讲怎么弄:

第一步:完善模型的多对多关联

你现在的模型只定义了到中间表的hasMany关联,其实可以直接定义多对多关联,这更贴合你的表结构逻辑,后续查询也更方便:

修改Group模型

class Group extends Model {
    protected $table = 'groups';
    protected $fillable = [ 'name' ];

    public function departmentGroups() {
        return $this->hasMany(DepartmentGroup::class, 'group_id','id');
    }

    // 添加多对多关联
    public function departments() {
        return $this->belongsToMany(Department::class, 'department_group', 'group_id', 'department_id');
    }
}

修改Department模型

class Department extends Model {
    protected $table = 'departments';
    protected $fillable = [ 'name' ];

    public function departmentGroups() {
        return $this->hasMany(DepartmentGroup::class, 'department_id','id');
    }

    // 添加多对多关联
    public function groups() {
        return $this->belongsToMany(Group::class, 'department_group', 'department_id', 'group_id');
    }
}

第二步:实现未关联部门的查询

有了多对多关联后,你可以用两种常用方式获取未关联指定分组的部门:

方法1:使用whereDoesntExist(推荐,单查询更高效)

这种方式会生成一条子查询,直接在数据库层面过滤出未关联的记录,性能更好:

// 指定要查询的分组ID
$targetGroupId = 1;

$unlinkedDepartments = Department::whereDoesntExist(function ($query) use ($targetGroupId) {
    $query->select(DB::raw(1))
          ->from('department_group')
          ->whereColumn('department_group.department_id', 'departments.id')
          ->where('department_group.group_id', $targetGroupId);
})->get();

方法2:利用关联获取已关联ID再排除(代码更直观)

先通过分组的关联获取已绑定的部门ID,再用whereNotIn排除这些ID:

$targetGroupId = 1;

// 获取该分组已关联的部门ID集合
$linkedDepartmentIds = Group::find($targetGroupId)->departments()->pluck('departments.id');

// 获取未关联的部门
$unlinkedDepartments = Department::whereNotIn('id', $linkedDepartmentIds)->get();

如果你不想修改现有关联?

要是你暂时不想添加多对多关联,只用现有的模型结构也能实现,写法类似方法1的子查询:

$targetGroupId = 1;

$unlinkedDepartments = Department::whereNotIn('id', function ($query) use ($targetGroupId) {
    $query->select('department_id')
          ->from('department_group')
          ->where('group_id', $targetGroupId);
})->get();

不管哪种方式,都能完美实现你要的效果:针对Group1返回Department2、Department3,针对Group2返回Department1、Department3。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:27:41