Skip to content

Commit

Permalink
fix: hasMany relationships are not eager loading properly (#116)
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharygolba committed May 21, 2016
1 parent 11cb766 commit 0f64cc8
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 18 deletions.
4 changes: 2 additions & 2 deletions src/packages/database/collection/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { entries } = Object;
class Collection extends Array {
constructor({ model, records = [], related = {} } = {}) {
const { length } = records;
const { modelName, primaryKey } = model;
const { tableName, primaryKey } = model;

super(length);
insert(this, records);
Expand All @@ -14,7 +14,7 @@ class Collection extends Array {
entries(related)
.forEach(([name, relatedRecords]) => {
const match = relatedRecords
.filter(({ [`${modelName}.${primaryKey}`]: pk }) => {
.filter(({ [`${tableName}.${primaryKey}`]: pk }) => {
return pk === row[primaryKey];
})
.map(relatedRecord => {
Expand Down
7 changes: 2 additions & 5 deletions src/packages/database/model/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import Promise from 'bluebird';
import { dasherize, pluralize } from 'inflection';

import Collection from '../collection';
Expand Down Expand Up @@ -439,10 +438,8 @@ class Model {
});
}

[records, related] = await Promise.all([
records,
fetchHasMany(this, related)
]);
records = await records;
related = await fetchHasMany(this, related, records);

return new Collection({
records,
Expand Down
25 changes: 14 additions & 11 deletions src/packages/database/model/utils/fetch-has-many.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import Promise from 'bluebird';
import formatSelect from './format-select';
import { sql } from '../../../logger';

export default async function fetchHasMany(model, related) {
export default async function fetchHasMany(model, related, records) {
const {
table,
tableName,
modelName,
primaryKey,

store: {
debug
}
Expand All @@ -19,20 +19,23 @@ export default async function fetchHasMany(model, related) {
attrs,
relationship: {
foreignKey,
model: relatedModel
model: relatedModel,

model: {
table,
tableName: relatedTableName
}
}
} = included;

const query = table()
.select(
`${tableName}.id AS ${modelName}.id`,
...formatSelect(relatedModel, attrs, `${name}.`)
...formatSelect(relatedModel, attrs, `${name}.`),
`${relatedTableName}.${foreignKey} AS ${tableName}.${primaryKey}`
)
.innerJoin(
relatedModel.tableName,
`${relatedModel.tableName}.${foreignKey}`,
'=',
`${tableName}.id`
.whereIn(
`${relatedTableName}.${foreignKey}`,
records.map(({ [primaryKey]: pk }) => pk)
);

if (debug) {
Expand Down

0 comments on commit 0f64cc8

Please sign in to comment.