首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用sequelize-typescript从单个字段引用多个模型?

如何使用sequelize-typescript从单个字段引用多个模型?
EN

Stack Overflow用户
提问于 2018-10-15 18:27:09
回答 1查看 850关注 0票数 1

我希望将来有多个Address用于PersonLocationPlace中的任何一个,也可能用于其他实体类型。我希望在我的Address模型上有一个字段,它指向地址相关的任何东西的id,而不必有personIdlocationIdplaceId等。在每个Address上,而他们只会使用其中的一个。

我的表结构如下所示:

addresses.entityId => people.id | locations.id | places.id

如何在sequelize-typescript中使用@ForeignKey对此进行建模

我的模型是这样的:

代码语言:javascript
复制
@Table
class Address extends Model<Address> {
  @Column({
    type: DataType.UUID,
    allowNull: false,
    primaryKey: true,
    unique: true,
    defaultValue: DataType.UUIDV4
  })
  id: string;

  @ForeignKey // ... ??
  entityId: string;
}

@Table
class Person extends Model<Person> {
  @Column({
    type: DataType.UUID,
    allowNull: false,
    primaryKey: true,
    unique: true,
    defaultValue: DataType.UUIDV4
  })
  id: string;
}

@Table
class Location extends Model<Location> {
  @Column({
    type: DataType.UUID,
    allowNull: false,
    primaryKey: true,
    unique: true,
    defaultValue: DataType.UUIDV4
  })
  id: string;
}

@Table
class Place extends Model<Place> {
  @Column({
    type: DataType.UUID,
    allowNull: false,
    primaryKey: true,
    unique: true,
    defaultValue: DataType.UUIDV4
  })
  id: string;
}
EN

回答 1

Stack Overflow用户

发布于 2018-11-27 22:14:49

在这种Sequelize Typescript情况下,可以多次指定自定义装饰器,所以如果您希望将一个列引用到多个模型,那么可以多次指定@ForeignKey,就像我给出的这个代码片段一样。你可以这样做:

代码语言:javascript
复制
@Table
class Address extends Model<Address> {
    @Column({
      type: DataType.UUID,
      allowNull: false,
      primaryKey: true,
      unique: true,
      defaultValue: DataType.UUIDV4
    })
    id: string;
    @ForeignKey(() => Person)
    @ForeignKey(() => Location)
    @ForeignKey(() => Place)
    @Column({})
    public entityId: string;
} 

参考:Sequelize Typescript Documentation

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52814646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档