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.
The Sequelize belongsToMany() method is used to create a Many-To-Many association between two tables. Two tables that have a Many-To-Many relationship require a third table that acts as the junction or join table. Each record in the junction table will keep track of the primary keys of both models.
To create a One-To-One relationship, the hasOne and belongsTo associations are used together; To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.
After Sequelize 5+, findById()
is replaced by findByPk()
Ledger.findByPk(22).then(ledger=>{
ledger.setCoins([1,2]).then(sc=>{
console.log(sc);
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With