Boris K
Boris K

Reputation: 3580

Bookshelf.js: one-to-many relationship setup

I'm using Bookshelf for an ORM with MySQL. I've got endpoints and organizations. Each endpoint belongs to an organization, and an organization has many endpoints. I'm trying to fetch a list of endpoints with their associated organization(s.) This is returning the following error:

"A valid target model must be defined for the endpoint belongsTo relation"

Here's my fetchAll request:

Endpoint
            .where('organization_id', req.user.attributes.organization_id)
            .fetchAll({require: true,withRelated: ['settings', 'organization']})
            .then((endpoints) => {
                ReS(res, {
                    endpoints
                }, 200);
            })

Here's my endpoint model:

'use strict';

const bookshelf = require('../config/bookshelf_instance');
const Organization = require('./organization');
const Settings = require('./endpoint_settings');
const Group = require('./endpoint_group');

module.exports = bookshelf.Model.extend({
    tableName: 'endpoint',
    organization () {
        return this.belongsTo(Organization, 'id');
    },
    settings () {
        return this.hasOne(Settings, 'id');
    },
    group () {
        return this.belongsToMany(Group, 'map_endpoint_endpoint_group');
    }
});

Here's my organization model:

'use strict';

const bookshelf = require('../config/bookshelf_instance');
const Endpoint = require('./endpoint');
const User = require('./user');
const Group = require('./endpoint_group');

module.exports = bookshelf.Model.extend({
    tableName: 'organization',
    endpoints () {
        return this.hasMany(Endpoint, 'organization_id');
    },
    users () {
        return this.hasMany(User, 'organization_id');
    },
    groups () {
        return this.hasMany(Group, 'organization_id');
    }
});

Upvotes: 0

Views: 1067

Answers (1)

devius
devius

Reputation: 3016

You should remove the id from the Endpoint model's relation specifications, since that seems to be the primary key, not the foreign key. The foreign key is also organization_id by default which is what you want. It should match what you have in the opposite relation (hasMany in this case).

From the documentation, the second argument to belongsTo is the:

ForeignKey in this model. By default, the foreignKey is assumed to be the singular form of the Target model's tableName, followed by _id.

The target model's table name is organization, which means the foreign key is organization_id by default.

Upvotes: 1

Related Questions