首页 文章

如何使用Sequelize belongsToMany关联?

提问于
浏览
11

我有项目和用户 .

用户可以拥有许多项目 .

一个项目可以有多个用户 .

我尝试使用belongsToMany关联对此进行建模 .

在我的服务器上,我定义了这样的关联:

user.belongsToMany(project, {
  through: 'writer_of_project'
  foreign-key: 'user'
  as: \projects
});

project.bbelongsToMany(user, {
  through: 'writer_of_project'
  foreign-key: 'project'
  as: 'writers'
});

在我的客户端,它看起来像这样:

user: {
  id:       1,
  ...
  projects: [1,2,3]
}

project: {
  id:     1,
  ...
  writers: [1,4,5]
}

在服务器上,关联需要第三个表来存储关联,而Sequelize似乎不允许我从中包含相应的模型 .

如果我用 include:[user] 运行 project.find(1) 我得到

用户与项目无关!

如果我尝试将上面示例中的项目放入update方法中 . 用户属性被简单地忽略(我期望一个project.setUsers(projectUpdate.users在后台发生) .

What is the right way to deal with the loading and updating of these associations?

1 回答

  • 16

    当您为关联提供别名( as )时,您还需要将其提供给包含:

    project.belongsToMany(user, {
      through: 'writer_of_project'
      foreign-key: 'project'
      as: 'writers'
    });
    
    project.find({
      where: { id: 1 },
      include: [ { model: User, as: 'writers' } ]
    });
    

    或者你可以保存关联:

    Project.writersAssociation = project.belongsToMany(user, {
      through: 'writer_of_project'
      foreign-key: 'project'
      as: 'writers'
    });
    
    project.find({
      where: { id: 1 },
      include: [ project.writersAssociation ]
    });
    

相关问题