objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Relation's owner is not a subclass of Model

Open raadecki opened this issue 8 years ago • 6 comments

Hello I have following model structure:

class BaseModel extends Model {
}

class DataSubjectCategory extends BaseModel {
      static get relationMappings() {
		return {
			dataSubjectCategorySubjectTypes: {
				relation: BaseModel.HasManyRelation,
				modelClass: DataSubjectCategorySubjectType,
				join: {
					from: 'subject.id',
					to: 'subject_subjecttype.subject',
				},
			},
		};
	}
}

In integration tests I want to insert test data to db

const DATA_SUBJECT_CATEGORIES = [
	{
		id: 1,
		name: 'subject category 1',
	},
	{
		id: 2,
		name: 'subject category 2',
	},
];

during this operation I'm getting DataSubjectCategory.relationMappings.dataSubjectCategorySubjectTypes: Relation's owner is not a subclass of Model error. I've tried to investigate it by myself and only thing I've found is that Model reference that I use for BaseModel extension doesn't match SuperModel.

I'm using node v 6.11.0 with hapijs lab testing framework

raadecki avatar Jan 04 '18 10:01 raadecki

You probably have a circular dependency (a require loop). Reopen this if the problem remains after you fix that.

koskimas avatar Jan 04 '18 10:01 koskimas

We have done a lot of searching for circular dependencies but can't find any.

One weird thing about this problem is that this error only appears if we try to insert new models solely in the beforeEach hook.

If we first insert in before hook and then utilize beforeEach there is no problem, likewise if only using the before hook. So if this was due to circular dep I guess inserting in the before hook should generate the same problem.

This is not much information to go on, but if it rings any bells please let us know :)

Our current solution is to insert and remove a dummy model in before and then go on as usual.

johannessjoberg avatar Jan 12 '18 13:01 johannessjoberg

Hello, I have the same problem, i searched and implement all suggested solutions but no solution so far.

I'am getting this error;

Post.relationMappings.assets: Relation's owner is not a subclass of Model

Can you help me this one please @koskimas ? Here is my models

BaseModel.js

const { Model } = require('objection');
const { DBErrors } = require('objection-db-errors');
const { master } = require('../../db');


class BaseModel extends DBErrors(Model) {
}

BaseModel.knex(master)

module.exports = {
    BaseModel
};

Post.js

const { BaseModel } = require("./BaseModel");

class Post extends BaseModel {

    static get tableName() {
        return 'post';
    }

    static get relationMappings() {
        const Asset = require('./Asset');
        const Customer = require('./Customer');

        return {
            '_customer': {
                relation: BaseModel.BelongsToOneRelation,
                modelClass: Customer,
                join: {
                    from: 'post.id',
                    to: 'customer.id'
                }
            },
            'assets': {
                relation: BaseModel.ManyToManyRelation,
                modelClass: Asset,
                join: {
                    from: 'post.id',
                    through: {
                        from: 'post_asset.post',
                        to: 'post_asset.asset'
                    },
                    to: 'asset.id'
                }
            }
        }
    }
}

module.exports = Post;

Asset.js

const { BaseModel } = require("./BaseModel");

class Asset extends BaseModel {
    static get tableName() {
        return 'asset';
    }
}

module.exports = Asset;

Customer.js

const { BaseModel } = require('./BaseModel');

class Customer extends BaseModel {
    static get tableName() {
        return 'customer';
    }

    static get relationMappings() {
        const CustomerInformation = require('./CustomerInformation');
        const GameProfile = require('./GameProfile');
        return {
            info: {
                relation: BaseModel.HasOneRelation,
                modelClass: CustomerInformation,
                join: {
                    from: 'customer.id',
                    to: 'customerinformation.customer'
                }
            },
            profiles: {
                relation: BaseModel.HasManyRelation,
                modelClass: GameProfile,
                join: {
                    from: 'customer.id',
                    to: 'gameprofile.customer'
                }
            }
        }
    }
}

module.exports = Customer;

LikeConnection.js

const { BaseModel } = require("./BaseModel");

class LikeConnection extends BaseModel {
    static get tableName() {
        return 'likeconnection'
    }
}

module.exports = LikeConnection;

Here is implementation,

const trxResult = await transaction(LikeConnection.knex(), async (trx) => {
                const like = await LikeConnection.query(trx).insert({
                    ...insertData
                });
                await Post.query(trx)
                    .patch({ likeCount: raw('likeCount + 1') })
                    .where('id', postId)

                const post = await Post.query(trx)
                                       .eager('[assets, _customer as customer .[info, profiles]]')
                                       .where('id', postId)
                                       .first()
                return post;
            });

rewebcan avatar Jun 10 '19 11:06 rewebcan

I have the same issue

any news?

aserhii87 avatar Aug 02 '19 21:08 aserhii87

The reason why this issue was closed with the remark "you probably have a circular dependency issue", is because there aren't many other possibilities here.

When you have a circular reference, the way that gets handled is one of the require statements actually returns an empty object (this is the way Node handles it, not an objection behavior, meaning there's basically nothing objection can do about it but recommend some specific workarounds). inside the relationMappings, when you try and pass it as a model, it does a runtime check to see if the class you're passing extends Model at some point. When it's an empty object, obviously this check fails.

The way to debug this error message is to add a breakpoint (or a util inspect/console output) of all of the models being provided to modelClass inside your relationMappings functions. Ensure that absolutely all of them have Model at some point in the prototype chain (verifiying this by looking for .query on the immediate item can also work).

If you look over every single item passed to modelClass, and you're still getting this error, then it'd be great if you could provide a small repo that reproduces this problem. If there's an edge case producing a bug, it'd be great to resolve; however with just incomplete code snippets that have been provided so far, we can't do much more than assume there's been a misconfiguration somewhere simply because there's basically no other way this error occurs.

mordof avatar Aug 03 '19 00:08 mordof

I should add that the only other way I know this error would occur (aside from a circular dependency) is if you provided a class which actually didn't extend Model anywhere. Again though, that'd be a misconfiguration.

mordof avatar Aug 03 '19 00:08 mordof