'How to model one-to-many association in sequelize?
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...
Solution 1:[1]
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
Solution 2:[2]
it depends on how you have structured the database, this would do thought..
paper.hasOne(term,{as:"PaperTerm"})
Solution 3:[3]
Well that's great that you had figured out how it works but it would have been correct if you had used Paper.belongsTo(Term); instead of Paper.hasOne( Term );
Here is the reference if you'd like to read more about
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rafa0809 |
| Solution 2 | |
| Solution 3 | IT ACADEMY |
