Consider the following models:
考虑以下模型:
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'});
Is there a way to query the UserLocation
table for a specific UserId
and get the corresponding Locations
. Something like:
有没有办法查询UserLocation表中的特定UserId并获取相应的位置。就像是:
SELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8
SELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8
From what I can find you can do something similar to:
从我能找到的你可以做类似的事情:
Location.findAll({
include: [{
model: User,
where: {
_id: req.user._id
}
}]
}).then( loc => {
console.log(loc);
});
However, this returns the Locations
, UserLocation
junctions, and User
which it is joining the User
table when I do not need any user information and I just need the Locations
for that user. What I have done is working, however, the query against the junction table is prefered instead of the lookup on the User
table.
但是,当我不需要任何用户信息时,这将返回它正在加入User表的Locations,UserLocation联结和User,我只需要该用户的Locations。我所做的是工作,但是,优先选择针对联结表的查询,而不是在User表上进行查找。
I hope this is clear. Thanks in advance.
我希望这很清楚。提前致谢。
Edit
I actually ended up implementing this in a different way. However, I am still going to leave this as a question because this should be possible.
我实际上最终以不同的方式实现了这一点。但是,我仍然会将此作为一个问题,因为这应该是可能的。
1 个解决方案
#1
3
declaring junction table as separate class, something like this
将联结表声明为单独的类,类似这样
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'});
then you can query junction table same as any other model.
然后你可以像任何其他模型一样查询联结表。
#1
3
declaring junction table as separate class, something like this
将联结表声明为单独的类,类似这样
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'});
then you can query junction table same as any other model.
然后你可以像任何其他模型一样查询联结表。