Jus*_*ber 9 javascript mysql node.js express sequelize.js
考虑以下模型:
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'});
Run Code Online (Sandbox Code Playgroud)
有没有办法查询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);
});
Run Code Online (Sandbox Code Playgroud)
然而,这种返回Locations,UserLocation路口,并且User它被加入User表时,我不需要任何用户信息,我需要的只是Locations该用户.我所做的是工作,但是,首选查询结点表而不是表上的查找User.
我希望这很清楚.提前致谢.
编辑
我实际上最终以不同的方式实现了这一点.但是,我仍然会将此作为一个问题,因为这应该是可能的.
将联结表声明为单独的类,如下所示
var UserLocation = sequelize.define('UserLocation', {
//you can define additional junction props here
});
User.belongsToMany(Location, {through: 'UserLocation', foreignKey: 'user_id'});
Location.belongsToMany(User, {through: 'UserLocation', foreignKey: 'location_id'});
Run Code Online (Sandbox Code Playgroud)
然后您可以像任何其他模型一样查询联结表。