我有两个以这种方式相关的表:
联赛
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 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);
});
});
});
如何检索有特定用户的联赛?
答案 0 :(得分:2)
您应该将where
添加到随附的模型中:
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);
});
});
});
<强>更新强>
它不是很好,但我知道,没有更好的解决方案:
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);
});
});
});