10
votes

I set up two models in sequelize that have a many-to-many relationship. Sequelize created the join table correctly, but I'm not able to insert into it. 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. 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. That code is below.

My two models are Coin and 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? I could write a custom function but I know there must be a way to do it.

2

2 Answers

10
votes

Well, I solved the problem with setCoins, above. Apparently it takes id numbers and not objects, so this works:

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.

4
votes

2019+

After Sequelize 5+, findById() is replaced by findByPk()

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