我有以下实体:
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"});
两个问题:
我正在进行以下查询:
Course.findAll({include:[{model:GroupHasCourse, as:"GroupsOnCourses"}]}).success(function(courses){
// courses[0].groupsOnCourses[0].GroupId
})
如何在该查询中获得左连接,因此我不需要再进行
的查询Group.find(courses[0].groupsOnCourses[0].GroupId)
答案 0 :(得分:2)
您是否需要连接表以获取更多数据?或者您只是连接Corse和Group?如果您只是想连接它们,您可以这样做:
Course.hasMany(Group)
Group.hasMany(Course)
这将自动为您创建连接表。如果你想要这样,你的下一个将是,你等待第一个alpha / beta / Sequelize 1.6.1,它将支持多对多关联的急切加载。该版本将在本周提供。
问候, sdepold
答案 1 :(得分: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)
})
})
})
})
})
})
})