【问题标题】:how to add a foreign key to sequelize model如何添加外键来续集模型
【发布时间】:2021-06-24 05:51:11
【问题描述】:

我需要将外键添加到引用健身房 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;
}

【问题讨论】:

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


    【解决方案1】:

    这取决于什么样的关联: 请查看此文档:https://www.npmjs.com/package/sequelize-typescript#model-association

    如果是一对多,那么就像这样:

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

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 2020-10-23
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2020-07-06
      相关资源
      最近更新 更多