@@ -116,8 +116,8 @@ module.exports =
116116
117117 if ( ( def . type === 'hasOne' || def . type === 'hasMany' ) && def . foreignKey ) {
118118 task = _this . findAll ( resourceConfig . getResource ( relationName ) , {
119- where : _defineProperty ( { } , def . foreignKey , instance ? { '==' : instance [ resourceConfig . idAttribute ] } : { 'in' : items . map ( function ( item ) {
120- return item [ resourceConfig . idAttribute ] ;
119+ where : _defineProperty ( { } , def . foreignKey , instance ? { '==' : instance [ def . localKey || resourceConfig . idAttribute ] } : { 'in' : items . map ( function ( item ) {
120+ return item [ def . localKey || resourceConfig . idAttribute ] ;
121121 } ) } )
122122 } , __options ) . then ( function ( relatedItems ) {
123123 if ( instance ) {
@@ -129,7 +129,7 @@ module.exports =
129129 } else {
130130 items . forEach ( function ( item ) {
131131 var attached = relatedItems . filter ( function ( ri ) {
132- return ri [ def . foreignKey ] === item [ resourceConfig . idAttribute ] ;
132+ return ri [ def . foreignKey ] === item [ def . localKey || resourceConfig . idAttribute ] ;
133133 } ) ;
134134 if ( def . type === 'hasOne' && attached . length ) {
135135 item [ def . localField ] = attached [ 0 ] ;
@@ -184,7 +184,10 @@ module.exports =
184184 if ( instance ) {
185185 var id = ( 0 , _object . get ) ( instance , def . localKey ) ;
186186 if ( id ) {
187- task = _this . find ( resourceConfig . getResource ( relationName ) , ( 0 , _object . get ) ( instance , def . localKey ) , __options ) . then ( function ( relatedItem ) {
187+ task = _this . findAll ( resourceConfig . getResource ( relationName ) , {
188+ where : _defineProperty ( { } , def . foreignKey || relationDef . idAttribute , { '==' : id } )
189+ } , __options ) . then ( function ( relatedItems ) {
190+ var relatedItem = relatedItems && relatedItems [ 0 ] ;
188191 instance [ def . localField ] = relatedItem ;
189192 return relatedItem ;
190193 } ) ;
@@ -197,13 +200,11 @@ module.exports =
197200 } ) ;
198201 if ( ids . length ) {
199202 task = _this . findAll ( resourceConfig . getResource ( relationName ) , {
200- where : _defineProperty ( { } , relationDef . idAttribute , {
201- 'in' : ids
202- } )
203+ where : _defineProperty ( { } , def . foreignKey || relationDef . idAttribute , { 'in' : ids } )
203204 } , __options ) . then ( function ( relatedItems ) {
204205 items . forEach ( function ( item ) {
205206 relatedItems . forEach ( function ( relatedItem ) {
206- if ( relatedItem [ relationDef . idAttribute ] === item [ def . localKey ] ) {
207+ if ( relatedItem [ def . foreignKey || relationDef . idAttribute ] === item [ def . localKey ] ) {
207208 item [ def . localField ] = relatedItem ;
208209 }
209210 } ) ;
0 commit comments