I am trying to create an index with multiple fields, one of the field is a foriegn key to another table. However i get the following error:
Error: Index "player_id_UNIQUE" contains column that is missing in the entity (Earning): player_id
Given that player_id is a foriegn key that im joining how do i handle this
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;
}
When i generate this entity and create the sql table (without the index) i see player_id
as one of the columns. But it appears that typeorm is not able to recognize right now with the index that player_id exists in the entity through the joincolumn relationship.
MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created. Information about foreign keys on InnoDB tables can also be found in the INNODB_FOREIGN and INNODB_FOREIGN_COLS tables, in the INFORMATION_SCHEMA database.
A unique index ensures the index key columns do not contain any duplicate values. A unique index may consist of one or many columns. If a unique index has one column, the values in this column will be unique. In case the unique index has multiple columns, the combination of values in these columns is unique.
You can include the foreign key creation while creating the table using CREATE TABLE T-SQL statement or create it after the table creation using ALTER TABLE T-SQL statement.
Right-click the table on which you want to create a unique index and select Design. On the Table Designer menu, select Indexes/Keys. In the Indexes/Keys dialog box, click Add. Select the new index in the Selected Primary/Unique Key or Index text box.
This is completely undocumented so it took some playing around until I stumbled upon the correct syntax. You can actually use sub-properties in index definitions:
@Index("player_id_UNIQUE", ["player.id", "period", "year"], { unique: true })
That way, player.id
is automatically mapped to player_id
in the resulting SQL:
CREATE UNIQUE INDEX "player_id_UNIQUE" ON "user_earning" ("player_id", "period", "year")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With