Skip to content

Commit 1f4f2bf

Browse files
committed
Add support for specifying other key (local or foreign) of a relation instead of always using the idAttribute when loading "with" relations
1 parent b39eda5 commit 1f4f2bf

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

src/index.js

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ function loadWithRelations (items, resourceConfig, options) {
5454
task = this.findAll(resourceConfig.getResource(relationName), {
5555
where: {
5656
[def.foreignKey]: instance ?
57-
{ '==': instance[resourceConfig.idAttribute] } :
58-
{ 'in': items.map(item => item[resourceConfig.idAttribute]) }
57+
{ '==': instance[def.localKey || resourceConfig.idAttribute] } :
58+
{ 'in': items.map(item => item[def.localKey || resourceConfig.idAttribute]) }
5959
}
6060
}, __options).then(relatedItems => {
6161
if (instance) {
@@ -66,7 +66,7 @@ function loadWithRelations (items, resourceConfig, options) {
6666
}
6767
} else {
6868
items.forEach(item => {
69-
let attached = relatedItems.filter(ri => ri[def.foreignKey] === item[resourceConfig.idAttribute])
69+
let attached = relatedItems.filter(ri => ri[def.foreignKey] === item[def.localKey || resourceConfig.idAttribute])
7070
if (def.type === 'hasOne' && attached.length) {
7171
item[def.localField] = attached[0]
7272
} else {
@@ -116,7 +116,12 @@ function loadWithRelations (items, resourceConfig, options) {
116116
if (instance) {
117117
let id = get(instance, def.localKey)
118118
if (id) {
119-
task = this.find(resourceConfig.getResource(relationName), get(instance, def.localKey), __options).then(relatedItem => {
119+
task = this.findAll(resourceConfig.getResource(relationName), {
120+
where: {
121+
[def.foreignKey || relationDef.idAttribute]: { '==': id }
122+
}
123+
}, __options).then(relatedItems => {
124+
let relatedItem = relatedItems && relatedItems[0];
120125
instance[def.localField] = relatedItem
121126
return relatedItem
122127
})
@@ -126,14 +131,12 @@ function loadWithRelations (items, resourceConfig, options) {
126131
if (ids.length) {
127132
task = this.findAll(resourceConfig.getResource(relationName), {
128133
where: {
129-
[relationDef.idAttribute]: {
130-
'in': ids
131-
}
134+
[def.foreignKey || relationDef.idAttribute]: { 'in': ids }
132135
}
133136
}, __options).then(relatedItems => {
134137
items.forEach(item => {
135138
relatedItems.forEach(relatedItem => {
136-
if (relatedItem[relationDef.idAttribute] === item[def.localKey]) {
139+
if (relatedItem[def.foreignKey || relationDef.idAttribute] === item[def.localKey]) {
137140
item[def.localField] = relatedItem
138141
}
139142
})

0 commit comments

Comments
 (0)