2017-08-10 13 views
0

アソシエーションのフィールドに自分のフィールドまたはに適用される条件でモデルを見つける方法はありますか?モデルの条件とSequelizeのアソシエーションの条件を組み合わせる

与えられたモデルModelおよびAssociation(各Modelは1つのAssociationを持ちます)。

const Model = sequelize.define('model', { 
    name: sequelize.STRING, 
}); 

const Association = sequelize.define('association', { 
    name: sequelize.STRING, 
}); 

Association.belongsTo(Model); 
Model.hasOne(Association); 

私はどちらかがname等しい「テキスト」、またはは、「テキスト」に等しいnameAssociationを持っていたことを、すべてのModelのを見つけたいです。

これまでのところ、私は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' }, 
     ], 
    }, 
}); 
関連する問題