I'm new to Sequelize, and I'm trying to figure out, how should I model one-to-many relationship.
My problem is as follows: one term, many papers.
var Term = sequelize.define( 'Term', ... );
var Paper = sequelize.define( 'Paper', ... );
Let's assume I have a term. Each term can have many papers, and I'd like to add/remove papers for my term. I'd also like to get all the papers for the term.
var term;
...
term.getPapers( ... );
term.setPapers( ... );
term.addPaper( paper );
term.removePaper( paper );
Now, let's assume I have a paper. I'd like to get/set the term for my paper.
var paper;
...
paper.getTerm();
paper.setTerm();
How can it be achieved using sequelize? I've been studying docs for hours, and also looking for some glues in the net, but without any results. I find this kind of association very poorly documented in sequelize (one-to-one and many-to-many are way better).
Update:
All right, several hours later I worked out how it works:
Term.hasMany( Paper, { as: 'papers' } );
Paper.hasOne( Term );
Now we can do:
term.addPaper( paper );
term.removePaper( paper );
paper.getTerm()
.success( function( term )
{
...
});
paper.setTerm( term );
I've got used to Django, and it seems that Sequelize is FAR less mature, both in terms of code and documentation...
First you have to create the association. You did it correctly:
Term.hasMany( Paper, { as: 'papers' } );
Paper.hasOne( Term );
Then you have to sync this declarations:
sequelize.sync();
And now persist data. You need to save the objects before to associate it.
term.create()...
paper1.create()...
paper2.create()...
term.setPapers([paper1, paper2]).success(function() {
// saved!
})
Reference: http://docs.sequelizejs.com/en/1.7.0/docs/associations/#many-to-many-associations
it depends on how you have structured the database, this would do thought..
paper.hasOne(term,{as:"PaperTerm"})
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