如何基于关联Users表的TenantId筛选Staff数据?
在Sequelize中查询Staff时按关联User的TenantId过滤
问题场景
我有Users表和Staff表,Users表包含TenantId字段,Staff表通过UserId外键关联Users表。当前使用以下代码查询Staff及其关联的User信息:
const listofStaff = await staff.findAll({ include:[ { model: Users, attributes: ['TenantId'] }] } )
查询返回结果示例:
[ { "id": 1, "profession": "Dentist", "locations": "1", "services": "1", "note": "Good Man", "holidays": "Saturday", "createdAt": "2022-12-14T10:30:54.000Z", "updatedAt": "2022-12-14T10:30:54.000Z", "roleId": null, "UserId": 1, "timesheetId": null, "User": { "TenantId": 1 } } ]
现在需要添加WHERE TenantId = 2的过滤条件,该如何实现?
解决方案
要过滤关联表Users的TenantId字段,需在include配置中添加where选项,可根据业务需求选择以下两种方式:
方式1:左连接(保留所有Staff,仅关联符合条件的User)
如果希望返回所有Staff记录,仅当关联的User满足TenantId=2时才带出对应的User信息,直接在include块内添加where条件即可:
const listofStaff = await staff.findAll({ include: [ { model: Users, attributes: ['TenantId'], where: { TenantId: 2 } // 在此处添加关联表的过滤条件 } ] });
方式2:内连接(仅返回关联User符合条件的Staff)
如果只需要返回那些关联User的TenantId=2的Staff记录,需额外添加required: true(等同于SQL的INNER JOIN),过滤掉无符合条件关联User的Staff:
const listofStaff = await staff.findAll({ include: [ { model: Users, attributes: ['TenantId'], where: { TenantId: 2 }, required: true // 开启内连接,仅保留符合关联条件的Staff } ] });
内容的提问来源于stack exchange,提问作者Mohammed Saber
相关产品推荐
相关产品推荐

