2016-05-01 48 views
0

我有以下型号:遍历多个表使用sequelize

accountTable = sequelize.define('Accounts', {}) 

walletTable = sequelize.define('Wallets', { 
'accountId' : { 'type' : Sequelize.BIGINT, 'references' : { model : 'Accounts', 'referenceKey' : 'id'}, allowNull: false }, 
'balance' : { 'type' : Sequelize.DOUBLE} 

connection = sequelize.define('Connections', 
'accountId' : { type : Sequelize.BIGINT(11) , 'references' : { model : 'Accounts', 'referenceKey' : 'id'} }, 
'active' : { type: Sequelize.BOOLEAN } 
}) 

我想要做的就是谁具有相同的accountId在钱包和它们断开所有活动连接。

这是我正在做的SQL

select c.sessionName, w.balance from Connections as c inner join Wallets w on w.balance = 0 and w.accountId=t.accountId where t.active = 1; 

我试图使用关系做sequelize相同,我无法去实现它。我尝试了这两个表之间的belongsToMany关系,并且出现连接没有关系钱包的错误。

任何想法如何解决这个问题?

大加赞赏

+0

能否请你告诉我们你怎么了建模关系?因为查询确实取决于表之间的关系如何工作 –

回答

0

假设你有你的关系建模为

Accounts.hasOne(Wallets); 
Accounts.hasMany(Connections); 

Wallets.belongsTo(Accounts); 

Connections.belongsTo(Accounts); 

,那么你应该能够执行查询,如下

Connections.findAll({ 
    where: { active: true }, 
    include: [{ 
     model: Accounts, 
     required: true, 
     include: [{ 
      model: Wallets, 
      required: true 
     }] 
    }] 
})