用最简单的例子来说, Admin中有一个外键image_id,关联UploadImage的id.
Admin中是 belongsTo
UploadImage中是hasMany
注意Admin的意思是 admin.js , UploadImage的意思是 upload_image.js。 很多人不知道这个点,所以根本不可能正确创建出表哦!
如果要系统去学习:文档: http://docs.sequelizejs.com/manual/installation/getting-started.html
要注意代码中的: app.model.xxx : 这个xxx是文件名的转换名!! 规则是 upload_image.js 就是 UploadImage
所以代码是这样的: app.model.UploadImage.hasMany(...............................)
可别以为这里的 UploadImage 是app.model.define('UploadImage', ....), 其实是文件名的转化
切记,切记,切记。不然写错了,关联就不会对!!
> admin.js 如下:
'use strict' module.exports = app => { const { INTEGER, STRING, BOOLEAN } = app.Sequelize const Admin = app.model.define('Admin', { id: { type: INTEGER(11), primaryKey: true, allowNull: false, autoIncrement: true }, image_id: { type: INTEGER(11), allowNull: false } }, { timestamps: true, freezeTableName: true, tableName: 'admin' }) // 表关联要这样写 Admin.associate = function() { app.model.Admin.belongsTo(app.model.UploadImage, {foreignKey:'image_id', targetKey: 'id'}); } return Admin }
> upload_image.js 如下:
'use strict' module.exports = app => { const { INTEGER, STRING } = app.Sequelize const UploadImage = app.model.define('UploadImage', { id: { type: INTEGER(11), primaryKey: true, allowNull: false, autoIncrement: true } }, { timestamps: true, freezeTableName: true, tableName: 'upload_image' }) // 表关联要这样写 UploadImage.associate = function() { app.model.UploadImage.hasMany(app.model.Admin, { foreignKey: 'image_id', targetKey: 'id' }); } return UploadImage }