【问题标题】:How to create a unique index containing multiple fields where one is a foreign key如何创建包含多个字段的唯一索引,其中一个是外键
【发布时间】:2020-10-04 00:16:54
【问题描述】:

我正在尝试创建具有多个字段的索引,其中一个字段是另一个表的外键。但是我收到以下错误:

错误:索引“player_id_UNIQUE”包含在 实体(收入):player_id

鉴于 player_id 是我加入的外键,我该如何处理

import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryColumn } from "typeorm";
import { PersonPlayer } from "./PersonPlayer";
import { Team } from "./Team";

    @Entity()
    @Index("player_id_UNIQUE", ["player_id", "period", "year"], { unique: true })
    export class Earning {

        @PrimaryColumn({length: 36})
        id: string;

        @Column({nullable: true})
        year: number;

        @Column({type: 'decimal', nullable: true})
        amount: number;

        @Column({nullable: true, length: 45})
        period: string;

        @ManyToOne(() => Team, {nullable: true})
        @JoinColumn({name: 'team_id'})
        team: Team;


        @ManyToOne(() => PersonPlayer, {nullable: true})
        @JoinColumn({name: 'player_id'})
        player: PersonPlayer;

        @Column({nullable: true, length: 45})
        dtype: string;

    }

当我生成此实体并创建 sql 表(没有索引)时,我将 player_id 视为列之一。但是现在 typeorm 似乎无法通过 joincolumn 关系识别 player_id 存在于实体中的索引。

【问题讨论】:

  • 您是否设法解决了这个问题@Kay?我现在遇到了同样的问题,在官方文档中找不到答案。
  • @VincentvanderWeele 是的,我将player: personPlayer 更改为player_id: PersonPlayer。这对我们有用,因为我们的项目只是处理数据库迁移,尽管将 player 作为名称而不是 player_id 会更好。但是因为我们没有使用 orm 的其余部分来制作我们不介意的任何业务逻辑

标签: sql node.js typeorm


【解决方案1】:

这是完全没有记录的,所以在我偶然发现正确的语法之前花了一些时间。您实际上可以在索引定义中使用子属性:

@Index("player_id_UNIQUE", ["player.id", "period", "year"], { unique: true })

这样,player.id 在生成的 SQL 中自动映射到 player_id

CREATE UNIQUE INDEX "player_id_UNIQUE" ON "user_earning" ("player_id", "period", "year")

【讨论】:

  • 你是救世主
【解决方案2】:
@Index(["player.id", "period", "year"])

或者就这样做! ?

【讨论】:

    【解决方案3】:

    您可以在Earning 实体中显式声明player_id。您需要做的唯一更改是添加

    @Column()
    player_id: number
    

    player 定义之前。

    这样,TypeORM 将player_id 识别为可以在@Index 或@Unique 定义中使用的有效列。

    记录在案的行为:https://typeorm.io/#/relations-faq/how-to-use-relation-id-without-joining-relation

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 2015-02-24
      • 2017-02-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多