2017-08-10 49 views
0

有沒有方法通過適用於其關聯字段的自己的字段的條件查找模型?將模型的條件與其關聯的條件組合在Sequelize中

鑑於模型ModelAssociation,其中每個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\''), 
     ], 
    }, 
}); 

有沒有更好的方法?

回答

0

此功能在文檔中描述:Top level where with eagerly loaded models

Model.findAll({ 
    attributes: ['id', 'name'], 
    include: [{ 
     model: Association, 
     attributes: [], 
    }], 
    where: { 
     $or: [ 
      { name: 'test' }, 
      { '$association.name$': 'test' }, 
     ], 
    }, 
});