简体   繁体   English

如何在续集中建模一对多关联?

[英]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.我是 Sequelize 的新手,我正试图弄清楚,我应该如何建模一对多关系。

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?使用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).我发现这种关联在 sequelize 中记录得很差(一对一和多对多要好得多)。

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...我已经习惯了 Django,而且似乎 Sequelize 在代码和文档方面都不那么成熟......

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 参考: http//docs.sequelizejs.com/en/1.7.0/docs/associations/#many-to-many-associations

这取决于你如何构建数据库,这会想到..

paper.hasOne(term,{as:"PaperTerm"})

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);很好,你已经弄清楚它是如何工作的,但如果你使用Paper.belongsTo(Term);正确了。 instead of Paper.hasOne( Term );而不是Paper.hasOne( Term ); Here is the reference if you'd like to read more about如果您想了解更多信息,这里是参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM