如何在续集中建模一对多关联? [英] How to model one-to-many association in sequelize?

查看:42
本文介绍了如何在续集中建模一对多关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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();

如何使用 sequelize 实现?我已经研究了几个小时的文档,也在网上寻找一些胶水,但没有任何结果.我发现这种关联在 sequelize 中的记录非常少(一对一和多对多更好).

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).

更新:

好吧,几个小时后我弄清楚了它是如何工作的:

All right, several hours later I worked out how it works:

Term.hasMany( Paper, { as: 'papers' } );
Paper.hasOne( Term );

现在我们可以:

term.addPaper( paper );
term.removePaper( paper );

paper.getTerm()
  .success( function( term )
  {
    ...
  });
paper.setTerm( term );

我已经习惯了 Django,而且 Sequelize 似乎还不够成熟,无论是在代码还是文档方面......

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!
  })

参考:http://docs.sequelizejs.com/en/1.7.0/docs/associations/#many-to-many-associations

这篇关于如何在续集中建模一对多关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆