Skip to content

Commit

Permalink
fix: use singular association name to generate FK (#16142)
Browse files Browse the repository at this point in the history
  • Loading branch information
ephys committed Jun 18, 2023
1 parent f5a8815 commit 8f8f13e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/associations/belongs-to.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { Op } from '../operators';
import { getColumnName } from '../utils/format.js';
import { isSameInitialModel } from '../utils/model-utils.js';
import { cloneDeep, removeUndefined } from '../utils/object.js';
import { camelize, singularize } from '../utils/string.js';
import { camelize } from '../utils/string.js';
import { Association } from './base';
import type { AssociationOptions, SingleAssociationAccessors } from './base';
import { HasMany } from './has-many.js';
Expand Down Expand Up @@ -264,7 +264,7 @@ export class BelongsTo<
}

protected inferForeignKey(): string {
const associationName = singularize(this.options.as);
const associationName = this.options.name.singular;
if (!associationName) {
throw new Error('Sanity check: Could not guess the name of the association');
}
Expand Down
7 changes: 5 additions & 2 deletions packages/core/test/integration/associations/has-one.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -516,8 +516,11 @@ describe(Support.getTestDialectTeaser('HasOne'), () => {
});

expect(Object.keys(InternetOrders.getAttributes()).length).to.equal(2);
expect(InternetOrders.getAttributes().OrderId).to.be.ok;
expect(InternetOrders.getAttributes().OrdersId).not.to.be.ok;

// The model is named incorrectly.
// The modal name should always be singular, so here sequelize assumes that "Orders" is singular
expect(InternetOrders.getAttributes().OrdersId).to.be.ok;
expect(InternetOrders.getAttributes().OrderId).not.to.be.ok;
});
});
});
Expand Down
16 changes: 16 additions & 0 deletions packages/core/test/unit/associations/belongs-to.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,22 @@ describe(getTestDialectTeaser('belongsTo'), () => {
sequelize.addModels([Post, Author]);
});

it(`uses the model's singular name to generate the foreign key name`, () => {
const Book = sequelize.define('Book', {}, {
name: {
singular: 'Singular',
plural: 'Plural',
},
});

const Log = sequelize.define('Log', {}, {});

Log.belongsTo(Book);

expect(Log.getAttributes().PluralId).to.not.exist;
expect(Log.getAttributes().SingularId).to.exist;
});

describe('association hooks', () => {
let Projects: ModelStatic<any>;
let Tasks: ModelStatic<any>;
Expand Down

0 comments on commit 8f8f13e

Please sign in to comment.