0

我有以下实体:

var Group = sequelize.define("Group", { name: Sequelize.STRING });
var Course = sequelize.define("Course", { name: Sequelize.STRING });
var GroupHasCourse = sequelize.define("GroupHasCourse", { name: Sequelize.STRING });
var Student = sequelize.define("Group", {   name: Sequelize.STRING });

以及以下关联:

Course.hasMany(GroupHasCourse, { as: "GroupsOnCourses"});
Group.hasMany(GroupHasCourse, { as: "CoursesOnGroups"});
GroupHasCourse.hasMany(Student, { as: "Students"});

两个问题:

  1. 这是在小组-课程关系之间建立联系以使学生进入主题的最佳方式吗?
  2. 我正在执行以下查询:

    Course.findAll({include:[{model:GroupHasCourse, as:"GroupsOnCourses"}]}).success(function(courses){
        // courses[0].groupsOnCourses[0].GroupId
    })
    

    我怎样才能得到那个查询中的左连接,所以我不需要做另一个查询

    Group.find(courses[0].groupsOnCourses[0].GroupId)
    
4

2 回答 2

2

您是否需要连接表以获取更多数据,或者您只是连接 Corse 和 Group?如果你只想连接它们,你可以这样做:

Course.hasMany(Group)
Group.hasMany(Course)

这将自动为您创建连接表。如果你想要这种方式,你的下一个将是,你等待 Sequelize 1.6.1 的第一个 alpha/beta/whatever,它将支持多对多关联的急切加载。该版本将在一周内提供。

问候,斯德波尔德

于 2013-04-17T18:20:52.827 回答
0

所以这已经适用于 1.6.0:

var Sequelize = require('sequelize')
var sequelize = new Sequelize('sequelize_test', 'root')

var Group = sequelize.define("Group", { name: Sequelize.STRING })
var Course = sequelize.define("Course", { name: Sequelize.STRING })
var GroupHasCourse = sequelize.define("GroupHasCourse", { name: Sequelize.STRING })
var Student = sequelize.define("Group", {   name: Sequelize.STRING })

Course.hasMany(GroupHasCourse, { as: "GroupsOnCourses"})
Group.hasMany(GroupHasCourse, { as: "CoursesOnGroups"})
GroupHasCourse.hasMany(Student, { as: "Students"}).belongsTo(Group).belongsTo(Course)

sequelize.sync({ force: true }).success(function() {
  Group.create({ name: 'group' }).success(function(group) {
    Course.create({ name: 'course' }).success(function(course) {
      GroupHasCourse.create({ name: 'bla' }).success(function(groupHasCourse) {
        groupHasCourse.setGroup(group).success(function() {
          groupHasCourse.setCourse(course).success(function() {
            GroupHasCourse.findAll({
              include: [ Group, Course ]
            }).success(function(groupHasCourses) {
              console.log(groupHasCourses[0].values)
            })
          })
        })
      })
    })
  })
})
于 2013-04-19T05:25:37.567 回答