简体   繁体   English

Sequelize 插入连接表(多对多)

[英]Sequelize insert into join table (many-to-many)

I set up two models in sequelize that have a many-to-many relationship.我在 sequelize 中设置了两个具有多对多关系的模型。 Sequelize created the join table correctly, but I'm not able to insert into it. Sequelize 正确创建了连接表,但我无法插入其中。 I've been poring over this section of the docs: http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations but I can't get anything to work based on their examples.我一直在研究文档的这一部分: http : //docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations,但我无法根据他们的示例进行任何工作。 They don't have a many-to-many example, unfortunately.不幸的是,他们没有多对多的例子。

Next I tried to use the setModel functions, and that's producing an error from deep in the sequelize code which I can't figure out.接下来我尝试使用 setModel 函数,这在续集代码的深处产生了一个我无法弄清楚的错误。 That code is below.该代码如下。

My two models are Coin and Ledger.我的两个模型是 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);
    });
});

My models are related to each other using this code:我的模型使用以下代码相互关联:

Ledger.belongsToMany(Coin,{ through: 'ledger_coin'});
Coin.belongsToMany(Ledger, {through: 'ledger_coin'});

Can anyone give me some suggestions or point me on the right track for either using the get functions or the association options to write to the join table?任何人都可以给我一些建议或指出我使用get函数或关联选项写入连接表的正确轨道吗? I could write a custom function but I know there must be a way to do it.我可以编写一个自定义函数,但我知道一定有办法做到这一点。

Well, I solved the problem with setCoins , above.好吧,我用上面的setCoins解决了这个问题。 Apparently it takes id numbers and not objects, so this works:显然它需要 id 号而不是对象,所以这是有效的:

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

I'd still like to understand includes and associations better, though.不过,我仍然想更好地理解包含和关联。

2019+ 2019+

After Sequelize 5+, findById() is replaced by findByPk() Sequelize 5+后, findById()替换为findByPk()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM