How to define Many To Many relationship with custom foreign keys? Foreign keys must targeting on field, which is not Primary Key. Many To Many relationship connection same Table.
Main table
import { Table, Column, Model, DataType, BelongsToMany } from 'sequelize-typescript';
import { SourceTarget } from './sourcetarget.entity';
@Table
export class SourceEntity extends Model<SourceEntity> {
@Column({
type: DataType.STRING,
unique: true
})
stringKey: string;
@BelongsToMany(() => SourceEntity, () => SourceTarget, "sourceStringKey", "targetStringKey")
targets?: SourceEntity[];
@BelongsToMany(() => SourceEntity, () => SourceTarget, "targetStringKey", "sourceStringKey")
sources?: SourceEntity[];
}
Relationship table
import { Table, Column, Model, ForeignKey, DataType, BelongsTo } from 'sequelize-typescript';
import { SourceEntity } from "./source.entity";
@Table
export class SourceTarget extends Model<SourceTarget> {
@ForeignKey(() => SourceEntity)
@Column({
type: DataType.STRING,
})
sourceStringKey!: string;
@BelongsTo(() => SourceEntity, {
foreignKey: "sourceStringKey",
targetKey: "stringKey",
keyType: DataType.STRING,
})
source: SourceEntity;
@ForeignKey(() => SourceEntity)
@Column({
type: DataType.STRING,
})
targetStringKey!: string;
@BelongsTo(() => SourceEntity, {
foreignKey: "targetStringKey",
targetKey: "stringKey",
keyType: DataType.STRING,
})
target: SourceEntity;
}