Skip to content

Targetkey is not automatically generated in associations #666

Open
@koswarabilly

Description

Context

Lets say I have two tables countries and users. In countries there are columns like id, name, code. code is a unique column and an alpha-2 of the country (UK, US, etc). users is linked to countries via code.

What is generated

In users model

countryCode: {
          type: DataTypes.STRING(2),
          allowNull: false,
          references: {
            model: 'countries',
            key: 'code',
          },
          field: 'country_code',
},

In associations

users.belongsTo(countries, { as: 'countryCodeCountry', foreignKey: 'countryCode' });
countries.hasMany(users, { as: 'users', foreignKey: 'countryCode' });

With this associations, the Sequelize generate wrong query resulting in error of trying to compare character varying to bigint

What is expected to generate

users.belongsTo(countries, { as: 'countryCodeCountry', foreignKey: 'countryCode', targetKey: 'symbol' });
countries.hasMany(users, { as: 'users', foreignKey: 'countryCode' });

Am I missing configuration or I am doing it wrong?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions