使用sequelize遍历多个表

时间:2016-05-01 20:14:44

标签: mysql node.js sequelize.js

我有以下型号:

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 }
})

我尝试做的是获取所有与Wallet具有相同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;

我试图在使用关系的续集中做同样的事情而我无法实现它。我尝试了两个表之间的belongsToMany关系,我得到的错误Connection与Wallet无关。

知道如何解决这个问题吗?

非常感谢

1 个答案:

答案 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
        }]
    }]
})