我有以下列方式定义的三个模型:
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
}, {
tableName: 'user',
classMethods: {
associate: function(models) {
models.User.hasMany(models.RestaurantUser, {
foreignKey: 'userId'
});
}
}
});
return User;
};
module.exports = function(sequelize, DataTypes) {
var Restaurant = sequelize.define('Restaurant', {
name: DataTypes.STRING,
address: DataTypes.STRING,
city: DataTypes.STRING,
zipcode: DataTypes.STRING,
country: DataTypes.STRING,
latitude: DataTypes.FLOAT,
longitude: DataTypes.FLOAT
}, {
tableName: 'restaurant',
classMethods: {
associate: function(models) {
models.Restaurant.hasMany(models.RestaurantUser, {
foreignKey: 'restaurantId'
});
}
}
});
return Restaurant;
};
'use strict';
module.exports = function(sequelize, DataTypes) {
var RestaurantUser = sequelize.define('RestaurantUser', {
restaurantId: DataTypes.INTEGER,
userId: DataTypes.INTEGER
}, {
tableName: 'restaurantuser',
classMethods: {
associate: function(models) {
models.RestaurantUser.belongsTo(models.User);
models.RestaurantUser.belongsTo(models.Restaurant);
}
}
});
return RestaurantUser;
};
当我尝试查找用户的所有餐馆时,我会执行以下查询,但会引发错误:
错误:{SequelizeEagerLoadingError:餐厅与之无关 RestaurantUser!
我所做的查询是:
return models.RestaurantUser.findAll({
where: {
userId: id,
},
include: [{ model: models.Restaurant }],
})
.then(restaurants => res.status(200).send(restaurants))
.catch(err => {
logger.error(err, 'restaurant_get_error');
});