[eggjs/egg]typescript 关联两张表

2025-11-04 381 views
0
What happens?

const { STRING, INTEGER } = app.Sequelize; const model = { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, fileName: STRING(30), fileId: { type: INTEGER, unique: true, allowNull: false, references: { model: 'article', key: 'id', }, }, fileUrl: STRING, }; const Article = app.model.define('article', model); app.model.Article.hasOne(app.model.File, { foreignKey: 'fileId' }); return class extends Article { };

const model = { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, creator: STRING(30), content: TEXT, text: TEXT, title: STRING(40), created_at: DATE, updated_at: DATE, isShow: BOOLEAN, }; const File = app.model.define('file', model); app.model.File.belongsTo(app.model.Article, { foreignKey: 'id', targetKey: 'fileId' }); return class extends File {}; ``

复现步骤,错误日志以及相关配置 相关环境信息 操作系统: Node 版本:8.11.3 Egg 版本:2.23.0 Egg-sequelize 版本:5.2.0 Typescript版本:3.5.0

回答

9

@atian25

0

定义表关系放在associate 函数里面,因为执行app.model.define时, Article还没有被绑定到app.model上面

Article.associate = function() {
  app.model.Article.hasOne(app.model.File, { foreignKey: 'fileId' });
}
3

问题已有回答,我关掉先

6

定义表关系放在associate 函数里面,因为执行app.model.define时, Article还没有被绑定到app.model上面

Article.associate = function() {
  app.model.Article.hasOne(app.model.File, { foreignKey: 'fileId' });
}

但是会有这个报错呢

3

@daiyang123456 我也报这个错 解决了吗?

0

定义表关系放在associate 函数里面,因为执行app.model.define时, Article还没有被绑定到app.model上面

Article.associate = function() {
  app.model.Article.hasOne(app.model.File, { foreignKey: 'fileId' });
}

但是会有这个报错呢

我也报这个错。。请问解决了吗

0

@daiyang123456 我也报这个错 解决了吗?

请问您解决了吗?

0

@daiyang123456 我也报这个错 解决了吗?

请问您解决了吗?

Article: any = .....就可以了