将插入插入到连接表中(多对多)

fre*_*ver 7 postgresql node.js express sequelize.js

我在sequelize中设置了两个具有多对多关系的模型.Sequelize正确创建了连接表,但我无法插入其中.我一直在研究文档的这一部分:http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations但我根据他们的例子得不到任何工作.遗憾的是,他们没有多对多的例子.

接下来我尝试使用setModel函数,并且这在sequelize代码中产生了一个错误,我无法弄清楚.该代码如下.

我的两个模特是Coin和Ledger.

Ledger.findById(22).then(ledger=>{
    var c1 = Coin.findById(1);
    var c2 = Coin.findById(2);
    ledger.setCoins([c1,c2]).then(sc=>{
        console.log(sc);
    });
});
Run Code Online (Sandbox Code Playgroud)

我的模型使用以下代码相互关联:

Ledger.belongsToMany(Coin,{ through: 'ledger_coin'});
Coin.belongsToMany(Ledger, {through: 'ledger_coin'});
Run Code Online (Sandbox Code Playgroud)

任何人都可以给我一些建议或指出我使用get函数或关联选项写入连接表的正确轨道?我可以写一个自定义函数,但我知道必须有办法做到这一点.

fre*_*ver 8

好吧,我解决了setCoins上面的问题.显然它需要id号而不是对象,所以这有效:

Ledger.findById(22).then(ledger=>{
    ledger.setCoins([1,2]).then(sc=>{
        console.log(sc);
    });
});
Run Code Online (Sandbox Code Playgroud)

不过,我仍然希望更好地理解包含和关联.


Seb*_*rin 6

2019+

Sequelize 5+后,findById()被替换为findByPk()

Ledger.findByPk(22).then(ledger=>{
    ledger.setCoins([1,2]).then(sc=>{
        console.log(sc);
    });
});
Run Code Online (Sandbox Code Playgroud)