egg-sequelize 建立表之间的外键, 最好能提供完整的mysql用例
最近在构建users 和userprofiles表之间构建relationship的时候,一直无法自动创建userprofiles中的外键user_id, 按照官方用例已经分别创建文件文件:
app/model/user.js:
module.exports = app => {
const {
STRING,
INTEGER,
BOOLEAN,
DATE
} = app.Sequelize;
const User = app.model.define('User', {
username: {
type: STRING(30),
unique: true
},
password: STRING(72),
companyName: STRING(255),
accountExpired: BOOLEAN,
passwordExpired: BOOLEAN
}, {
classMethods: {
associate() {
User.hasOne(app.model.UserProfile);
}
}
});
User.sync({force: true})
return User;
}
app/model/userProfile.js:
module.exports = app => {
const {
STRING,
INTEGER,
BOOLEAN,
DATE
} = app.Sequelize;
const UserProfile = app.model.define('UserProfile', {
name: STRING(64),
address: STRING(255),
email: {
type: STRING(64),
isEmail: true
},
birthDay: DATE,
currentCity: STRING(255),
currentCountry: STRING(255),
}, {
classMethods: {
associate() {
UserProfile.belongsTo(app.model.User);
}
}
});
UserProfile.sync({force: true})
return UserProfile;
}
虽然两张表能顺利的创建起来,但是两个表之间并没有简历关联希望官方对于插件 egg-sequelize 给出详细点的实例。
有可能你说的这个问题属于sequelize的问题,而不属于egg。因为我认为egg只是了继承了sequelize的所有方法,而具体如何用只需要去参考sequelize的做法即可,也就是说egg-sequelize就是为了egg能用sequelize而已吧
恩,问题解决了,但是就是不知道应该在哪里统一的sync所有的表比较合适?
我个人是把 sync 操作放在 app.js 里。期待官方的最佳实践。
一样,不知道应该在哪里统一的sync所有的表比较合适?
@SF-Zhou 方便看下代码?
放在 app.js 是合适的,https://eggjs.org/zh-cn/basics/app-start.html
@SF-Zhou
麻烦问下,app.js里访问不到sync方法,可能是因为什么。部分代码如下。
app.js
// app.js
module.exports = app => {
app.beforeStart(function* () {
//同步数据库表
console.log(`同步数据表:` + ( app.Sequelize.sync == null) )
app.Sequelize.sync()
});
};
//config/plugin.js
'use strict';
exports.sequelize = {
enable: true,
package: 'egg-sequelize'
}
exports.proxyworker = {
enable: true,
package: 'egg-development-proxyworker',
};
//config/config.default.js
'use strict';
//数据库配置
exports.sequelize = {
dialect: 'mssql', // support: mysql, mariadb, postgres, mssql
database: 'node',
host: 'localhost',
port: '',
username: 'sa',
password: '',
}
//代理端口号
exports.proxyworker = {
port: 10086,
}
//合并导出配置
module.exports = appInfo => {
const config = {}
config.keys = appInfo.name + '_1493694003052_3077'
return Object.assign(exports, config)
}
@a304885433 写了 model 的话,在 app.js 里调用 app.model.ModelName.sync()。
@SF-Zhou 明白了,非常感谢,自己之前还是在model里写的,这样可以从model定义中分离出来。
@SF-Zhou 最近发现,原来挂载sequelize 的sync方法,被移植到了 app.Model.sync 这样可以同步所有表结构了。
在根目录下的app.js执行app.Model.sync()就好了
@callmesoul 之前就是没找到sync方法挂在哪里,官方文档哪里有app.Model的定义,我还是无意中发现的。。。
我也发现表之间无法建立关联,请问你是怎么解决的 @yugasun
@aasailan https://github.com/eggjs/egg-sequelize#full-example 请注意查看README文件。