Sequelize-typescript: how to use unique key instead of primary key in one-to-one assoction

Created on 13 Feb 2018  路  2Comments  路  Source: RobinBuschmann/sequelize-typescript

I have two model AdminUser, Organization, and I want to use unique key Organzation.code assoction AdminUser.organizationCode instead of primary key id

export class AdminUser extends Model<AdminUser> {
    @PrimaryKey
    @AutoIncrement
    @Column
    public id: number;

   @ForeignKey(() => Organization)
    public organizationCode: string;

    @BelongsTo(() => Organization, "organizationCode")
    public organization: Organization;
}

export class Organization extends Model<Organization> {
    @PrimaryKey
    @AutoIncrement
    @Column
    public id: number;

    @Unique
    @Column
    public code: string;

    @HasOne(() => AdminUser)
    public adminUser: AdminUser;
}

but sql query is still use organization.id associate
image

how to make right associate like AdminUser`.`organizationCode` = `organization`.`code

Most helpful comment

Hey @chaoxihailing, actually you need to use targetKey like so:

@BelongsTo(() => Organization, {targetKey: 'code'})

鈿狅笍But this doesn't seem to work with HasOne. Regarding this it is an issue with sequelize.

So you could use @HasMany as a workaround :/

All 2 comments

Hey @chaoxihailing, actually you need to use targetKey like so:

@BelongsTo(() => Organization, {targetKey: 'code'})

鈿狅笍But this doesn't seem to work with HasOne. Regarding this it is an issue with sequelize.

So you could use @HasMany as a workaround :/

thanks锛宨t can work normally

Was this page helpful?
0 / 5 - 0 ratings

Related issues

libvirtadept picture libvirtadept  路  4Comments

fareshan picture fareshan  路  3Comments

fareshan picture fareshan  路  3Comments

lilling picture lilling  路  4Comments

bschveitzer picture bschveitzer  路  5Comments