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

MikroORM多对多关系中如何查询未关联指定教师的学生

背景

我有两个实体:

@Entity({ tableName: 'students' })
export class StudentEntity {
  @Property()
  firstName: string;

  @Property()
  lastName: string;

  @ManyToMany({
  entity: () => TeacherEntity,
    pivotTable: 'students_to_teachers',
    joinColumn: 'student_id',
    inverseJoinColumn: 'teacher_id'
  })
  teachers = new Collection<TeacherEntity>(this);
}

以及:

@Entity({ tableName: 'teachers' })
export class TeacherEntity {
   @OneToOne(() => UserEntity, {
    owner: true,
    fieldName: 'user_id',
  })
  user: UserEntity;

  @ManyToMany({
    entity: () => StudentEntity,
    pivotTable: 'students_to_teachers',
    joinColumn: 'teacher_id',
    mappedBy: (s: StudentEntity) => s.teachers
  })
  students = new Collection<StudentEntity>(this);
}
需求

已知教师关联的UserEntity的userId,我可以通过以下代码查询所有与该教师关联的学生:

const students = await this.studentsRepo.find(
  {
    teachers: {
      user: {
        id: userId
      }
    }
  }
);
问题

现在我需要查询所有未与该教师关联的学生,尝试了如下代码但无法正常工作,请提供解决方案:

const students = await this.studentsRepo.find(
  {
    teachers: {
      user: {
        $ne: {
          id: userId
        }
      }
    }
  }
);
解决方案

你之前的写法逻辑有误,$ne会匹配那些至少有一个教师的用户ID不等于目标ID的学生,但这类学生可能同时关联了目标教师,不符合“未与该教师关联”的要求。

正确的做法是使用$not操作符,否定整个“关联目标教师”的条件,这样就能筛选出所有不存在与目标教师关联的学生(包括完全没有关联任何教师的学生):

const students = await this.studentsRepo.find({
  $not: {
    teachers: {
      user: {
        id: userId
      }
    }
  }
});

如果需要更高效的查询,也可以先获取目标教师的ID,再用$not匹配教师ID:

// 先获取目标教师实例
const targetTeacher = await this.teachersRepo.findOne({ user: { id: userId } });

// 查询未关联该教师的学生
const students = await this.studentsRepo.find({
  $not: {
    teachers: { id: targetTeacher.id }
  }
});

这两种写法都能准确筛选出未与指定教师关联的学生。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:13:17