在findAll中,Sequelize将返回与关联表的每个匹配行,而在findOne中,它只返回与查询条件匹配的一个行。为解决此问题,可以使用一个子查询来限制findAll匹配的行数,以便只返回一个。 在代码示例中,我们可以使用子查询来将findAll的行数限制为一个:
const result = await Model.findAll({
where: { someAttribute: 'someValue' },
include: [{
model: OtherModel,
where: { someOtherAttribute: 'someOtherValue' },
limit: 1 // This limits the parent rows to 1
}]
});
在这里,我们使用限制符“limit:1”来限制父行的数量。这个子查询只会选择一个关联的行,这样在findAll中就只会返回一个父行了。