【发布时间】:2016-07-23 15:41:26
【问题描述】:
考虑以下模型:
var User = sequelize.define('User', {
_id:{
type: Datatypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: Datatypes.STRING,
email:{
type: Datatypes.STRING,
unique: {
msg: 'Email Taken'
},
validate: {
isEmail: true
}
}
});
var Location= sequelize.define('Location', {
_id:{
type: Datatypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: Datatypes.STRING,
address: type: Datatypes.STRING
});
Location.belongsToMany(User, {through: 'UserLocation'});
User.belongsToMany(Location, {through: 'UserLocation'});
有没有办法在UserLocation表中查询特定的UserId并得到对应的Locations。比如:
SELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8
据我所知,您可以执行以下操作:
Location.findAll({
include: [{
model: User,
where: {
_id: req.user._id
}
}]
}).then( loc => {
console.log(loc);
});
但是,当我不需要任何用户信息并且我只需要该用户的 Locations 时,这将返回 Locations、UserLocation 连接和 User,它正在加入 User 表。我所做的是工作,但是,首选对联结表的查询,而不是在 User 表上的查找。
我希望这很清楚。提前致谢。
编辑
我实际上最终以不同的方式实现了这一点。但是,我仍然会将此作为一个问题,因为这应该是可能的。
【问题讨论】:
标签: javascript mysql node.js express sequelize.js