I am using Objection.js with Knex in a Node.js application and trying to pull data with a relationship. This has worked for me in the past, but on one of my tables it is saying the relationship does not exist:
A model class DashboardLayout doesn't have relation component
I have two tables, DashboardLayout and Component. DashboardLayout has a BelongsToOne relationship on Component. Here is how they are defined in the migration.
.createTable('components', table => {
table.increments();
table.string('name').notNullable();
table.integer('componentTypeId').references('id').inTable('componentTypes');
table.timestamps(true,true);
})
and
.createTable('dashboardLayouts', table => {
table.increments();
table.integer('x');
table.integer('y');
table.integer('w');
table.integer('h');
table.integer('dashboardId');
table.integer('componentId').references('id').inTable('components');
table.timestamps(true, true);
});
Then my DashboardLayout Model file looks like this:
const { Model } = require('objection');
const Component = require('./component');
class DashboardLayout extends Model {
static get tableName() {
return 'dashboardLayouts';
}
static relationMappings = {
componentType: {
relation: Model.BelongsToOneRelation,
modelClass: Component,
join: {
from: 'dashboardLayouts.componentId',
to: 'components.id'
}
}
}
}
module.exports = DashboardLayout;
But when I query the database with the following code it returns the error
A model class DashboardLayout doesn't have relation component
const layout = await DashboardLayout.query()
.select(
'dashboardLayouts.id',
'dashboardLayouts.x',
'dashboardLayouts.y',
'dashboardLayouts.w',
'dashboardLayouts.h',
'dashboardLayouts.dashboardId',
'dashboardLayouts.componentId'
)
.joinRelated({ component: true })
.where('dashboardLayouts.dashboardId', '=', id);
return res.json(layout);
Maybe I have been looking at it for too long but I cannot see why the relationship is not working.
Any help would be greatly appreciated.