将模型的条件与其关联的条件组合在Sequelize中
问题描述:
有没有方法通过适用于其关联字段的自己的字段或的条件查找模型?将模型的条件与其关联的条件组合在Sequelize中
鉴于模型Model
和Association
,其中每个Model
有一个Association
。
const Model = sequelize.define('model', {
name: sequelize.STRING,
});
const Association = sequelize.define('association', {
name: sequelize.STRING,
});
Association.belongsTo(Model);
Model.hasOne(Association);
我想找到所有Model
S,要么有一个name
等于“文本”,或有一个name
等于“文本”的Association
。
到目前为止,我想出了解决方案Sequelize.literal
,这看起来不够健壮。
Model.findAll({
attributes: ['id', 'name'],
include: [{
model: Association,
attributes: [],
}],
where: {
$or: [
{ name: 'test' },
Sequelize.literal('association.name = \'test\''),
],
},
});
有没有更好的方法?
答
此功能在文档中描述:Top level where with eagerly loaded models。
Model.findAll({
attributes: ['id', 'name'],
include: [{
model: Association,
attributes: [],
}],
where: {
$or: [
{ name: 'test' },
{ '$association.name$': 'test' },
],
},
});