node.js - 如何添加外键来 Sequelize 模型

标签 node.js database postgresql sequelize.js sequelize-typescript

我需要将外键添加到引用健身房 ID 的用户表中,
什么是正确的语法?

export class User extends Model<User> {
// user properties:
  @PrimaryKey
  @AutoIncrement
  @Column(DataType.INTEGER)
  public id: number;

  @AllowNull(false)
  @Column(DataType.STRING)
  public first_name: string;

  // here i need to reference the gym_id to the id from the gym table:

  @AllowNull(false)
  @Column(DataType.INTEGER)
 // @ForeignKey(Gym.id)
  public gym_id: number;
}

最佳答案

这取决于什么样的关联:
请查看此文档:https://www.npmjs.com/package/sequelize-typescript#model-association
如果是一对多,那么就像这样:

  @ForeignKey(() => Gym)
  @Column
  gym_id: number

  @BelongsTo(() => Gym)
  gym: Gym

关于node.js - 如何添加外键来 Sequelize 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66833228/

相关文章:

node.js - 当我使用带有 .stream() 的 mongo tailable 光标时,我的 CPU 过热

node.js - 运行我的代码时获得意外的 token ,该代码应该从 giphy 发布 gif

php - SQL 从数据库获取 Woocommerce 产品缩略图

ruby-on-rails-3 - 无法获得 Postgres.app 连接

ruby-on-rails - Rails 多表 ID 递增

javascript - 在 Javascript 中等待来自 JQuery $.each 中的异步嵌套函数的数据

javascript - 错误: 3 INVALID_ARGUMENT: Name 'Hello' does not match patterns DialogFlow

php - undefined index PHP和MYSQL

database - 具有数据库模式的SpecFlow集成测试

sql - 加入动态列名称