11import 'reflect-metadata' ;
2+ import { AssociationOptions , AssociationForeignKeyOptions , AssociationOptionsBelongsTo , AssociationOptionsBelongsToMany ,
3+ AssociationOptionsHasMany , AssociationOptionsHasOne , AssociationOptionsManyToMany } from 'sequelize' ;
24import { Model } from "../models/Model" ;
35import { ISequelizeForeignKeyConfig } from "../interfaces/ISequelizeForeignKeyConfig" ;
46import { ISequelizeAssociation } from "../interfaces/ISequelizeAssociation" ;
@@ -18,7 +20,9 @@ export function addAssociation(target: any,
1820 relation : string ,
1921 relatedClassGetter : ( ) => typeof Model ,
2022 as : string ,
21- foreignKey ?: string ,
23+ options ?: AssociationOptionsBelongsTo |
24+ AssociationOptionsBelongsToMany | AssociationOptionsHasMany |
25+ AssociationOptionsHasOne | AssociationOptionsManyToMany ,
2226 otherKey ?: string ,
2327 through ?: ( ( ) => typeof Model ) | string ) : void {
2428
@@ -42,7 +46,7 @@ export function addAssociation(target: any,
4246 throughClassGetter,
4347 through : through as string ,
4448 as,
45- foreignKey ,
49+ options ,
4650 otherKey
4751 } ) ;
4852}
@@ -52,11 +56,19 @@ export function addAssociation(target: any,
5256 */
5357export function getForeignKey ( _class : typeof Model ,
5458 association : ISequelizeAssociation ) : string {
59+ const options = association . options as AssociationOptions ;
5560
56- // if foreign key is defined return this one
57- if ( association . foreignKey ) {
61+ if ( options && options . foreignKey ) {
62+ const foreignKey = options . foreignKey ;
63+ // if options is an object and has a string foreignKey property, use that as the name
64+ if ( typeof foreignKey === 'string' ) {
65+ return foreignKey ;
66+ }
5867
59- return association . foreignKey ;
68+ // if options is an object with foreignKey.name, use that as the name
69+ if ( foreignKey . name ) {
70+ return foreignKey . name ;
71+ }
6072 }
6173
6274 // otherwise calculate the foreign key by related or through class
@@ -90,8 +102,10 @@ export function getForeignKey(_class: typeof Model,
90102 for ( const foreignKey of foreignKeys ) {
91103
92104 if ( foreignKey . relatedClassGetter ( ) === relatedClass ) {
93-
94- return foreignKey . foreignKey ;
105+ if ( typeof foreignKey . options === 'string' ) {
106+ return foreignKey . options ;
107+ }
108+ return ( foreignKey . options as any ) . name ;
95109 }
96110 }
97111
@@ -123,7 +137,7 @@ export function getAssociationsByRelation(target: any, relatedClass: any): ISequ
123137 */
124138export function addForeignKey ( target : any ,
125139 relatedClassGetter : ( ) => typeof Model ,
126- attrName : string ) : void {
140+ options : string | AssociationForeignKeyOptions ) : void {
127141
128142 let foreignKeys = getForeignKeys ( target ) ;
129143
@@ -134,7 +148,7 @@ export function addForeignKey(target: any,
134148
135149 foreignKeys . push ( {
136150 relatedClassGetter,
137- foreignKey : attrName
151+ options
138152 } ) ;
139153}
140154
0 commit comments