使用belongsToMany 关联对findAll 进行后续处理 [英] Sequelize findAll with belongsToMany association
本文介绍了使用belongsToMany 关联对findAll 进行后续处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个以这种方式相关的表:
I have two tables related in this way :
联赛
sequelize.define('league', {
name: {
type: DataTypes.STRING,
},
ownerId: {
type: DataTypes.INTEGER,
}
}, {
classMethods: {
associate: function(models) {
League.belongsToMany(models.user, {
constraints: false,
through: models.UserLeague,
});
}
}
}, {
freezeTableName: true
});
用户
sequelize.define('user', {
name: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING,
unique: true,
validate: {
isEmail: true
}
},
profile_picture: {
type: DataTypes.STRING
}
}, {
classMethods: {
associate: function(models) {
User.belongsToMany(models.league, {
constraints: false,
through: models.UserLeague,
});
}
}
}, {
freezeTableName: true
});
我想获取所有包含特定用户的联赛:我目前正在执行此操作,但出现错误 column League.users.id 不存在
>
I would like to get all the leagues that have a certain User in them : I'm doing this at the moment but I get the error column league.users.id does not exist
sequelize.transaction(function (t) {
return models.user.findOne({where: {email: req.query.email}}, {transaction: t}).then(function(user) {
return models.league.findAll({where: {'users.id': user.id}, include: [{model: models.user, as: 'users'}]}).then(function(leagues) {
res.json(leagues);
});
});
});
如何检索有特定用户的联赛?
How could I retrieve the leagues where there is a certain user ?
推荐答案
你应该将你的 where
添加到包含的模型中:
You should add your where
to the included model:
sequelize.transaction(function (t) {
return models.user.findOne({where: {email: req.query.email}}, {transaction: t}).then(function (user) {
return models.league.findAll({
include: [{
model: models.user,
as: 'users',
where: {
id: user.id
},
required: true
}]
}).then(function (leagues) {
res.json(leagues);
});
});
});
更新:
这不是很好,但我认为没有更好的解决方案:
Its' not really nice, but I thinik, there is no better solution:
sequelize.transaction(function (t) {
return models.user.findOne({where: {email: req.query.email}}, {transaction: t}).then(function (user) {
var _leagueIds = [];
return models.league.findAll({
include: [{
model: models.user,
as: 'users',
where: {
id: user.id
},
required: true
}]
})
.each(function (league) {
_leagueIds.push(league.id);
})
.then(function () {
return models.league.findAll({
where: {
id: _leagueIds,
},
include: [{
model: models.user,
as: 'users'
}]
});
})
.then(function (leagues) {
res.json(leagues);
});
});
});
这篇关于使用belongsToMany 关联对findAll 进行后续处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文