使用Sequelize的关联和嵌套查询来解决这个问题。例如,我们有两个模型:User和Task,其中Task模型有一个userId字段来关联User模型的主键。如果我们想要查询Task中所有userId为5的任务,我们可以这样写:
Task.findAll({
where: {
userId: 5,
'$User.name$': 'John'
},
include: [{
model: User,
attributes: ['name']
}]
});
上述代码中,我们通过include
选项将User模型包含进来,并通过attributes
选项指定要返回的字段。然后,在where子句中,我们可以使用$User.name$
来访问关联的User模型中的name字段。这将生成一个联接查询,检索所有userId为5且关联的用户名为John的任务。