Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize insert into join table (many-to-many)

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.

like image 747
fredrover Avatar asked Mar 19 '17 02:03

fredrover


People also ask

What does many belongs to many Sequelize?

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.

What is a one to many relationship in Sequelize?

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.


2 Answers

2019+

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

Ledger.findByPk(22).then(ledger=>{
    ledger.setCoins([1,2]).then(sc=>{
        console.log(sc);
    });
});
like image 77
Sebastien Horin Avatar answered Oct 26 '22 05:10

Sebastien Horin


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.

like image 21
fredrover Avatar answered Oct 26 '22 04:10

fredrover