所以我最近开始使用Sequelize,目前正在使用它。我有两个模型(User
& Photo
)基本上我尝试做的是从findAll
和user
做include: [ { model: 'photo' } ]
所以我得到了特定用户提交的所有照片。
用户模型:
var user = sequelize.define(configModels.user, {
userId: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
referenceces: {
model: 'photo',
key: 'userId'
}
},
name: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
}, {
classMethods: {
associate: function(models) {
user.hasMany(models.photo, { as: 'photo_fk', constraints: true });
}
},
freezeTableName: true // Model tableName will be the same as the model name
});
照片模特:
var photo = sequelize.define(configModels.photo, {
photoId: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
userId: {
type: DataTypes.INTEGER,
allowNull: false,
referenceces: {
model: 'user',
key: 'userId'
}
},
photo: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
photo.belongsTo(models.user, { as: 'user_fk', constraints: true });
}
},
freezeTableName: true // Model tableName will be the same as the model name
});
这是我运行findAll
方法的地方:
User.findAll({
include: [
{ model: 'photo' }
]
}).then(function(users){
console.log("Found all ids: ", users);
// callback(users);
}).catch(function(err){
console.log(err);
});
当我运行这个时,我得到一个错误,说两个模型没有关联?!像这样:
[Error: X is not associated to Y!]