ObjectionJS关系modelClass未定义

时间:2017-10-15 20:15:04

标签: node.js objection.js

我正在尝试更新useruser_profile之间的关系。我可以更新用户,但是当我尝试更新user_profile

时,我一直收到此错误消息

ERROR: Error: UserProfile.relationMappings.user: modelClass is not defined

据我所知,我已经模仿了文档和TypeScript示例中的示例,但有人能够理解为什么这不起作用吗?

我包含了查询,两种模型和用户配置文件迁移。 BaseModel的内容被注释掉,因此它等同于直接从Model继承,而jsonSchema仅用于验证,所以为了简洁我删除了它们。

更新

relationshipMappings移除UserProfile可以阻止错误发生,但由于我需要BelongsToOneRelation关系,我还在尝试。至少它似乎缩小到relationMappings上的UserProfile

查询

const user = await User.query() // <--- Inserts the user
  .insert({ username, password });

const profile = await UserProfile.query() <--- Throws error
  .insert({ user_id: 1, first_name, last_name });

模型

import { Model, RelationMappings } from 'objection';
import { BaseModel } from './base.model';
import { UserProfile } from './user-profile.model';

export class User extends BaseModel {
  readonly id: number;
  username: string;
  password: string;
  role: string;

  static tableName = 'users';

  static jsonSchema = { ... };

  static relationMappings: RelationMappings = {
    profile: {
      relation: Model.HasOneRelation,
      modelClass: UserProfile,
      join: {
        from: 'users.id',
        to: 'user_profiles.user_id'
      }
    }
  };

}

import { Model, RelationMappings } from 'objection';
import { BaseModel } from './base.model';
import { User } from './user.model';

export class UserProfile extends BaseModel {
  readonly id: number;
  user_id: number;
  first_name: string;
  last_name: string;

  static tableName = 'user_profiles';

  static jsonSchema = { ... };

  static relationMappings: RelationMappings = {
    user: {
      relation: Model.BelongsToOneRelation,
      modelClass: User,
      join: {
        from: 'user_profiles.user_id',
        to: 'users.id'
      }
    }
  };
}

移植

exports.up = function (knex, Promise) {
  return knex.schema
    .createTable('user_profiles', (table) => {
      table.increments('id').primary();

      table.integer('user_id')
        .unsigned()
        .notNullable();
      table.foreign('user_id')
        .references('users.id');

      table.string('first_name');
      table.string('last_name');

      table.timestamps(true, true);
    });
};

1 个答案:

答案 0 :(得分:3)

我会说那个

a)是循环依赖的问题或/和 b)导入路径存在问题

一种是在modelClass中使用绝对文件路径而不是构造函数。例如

 modelClass: __dirname + '/User'

modelClass: require('./User').default

看一下例子: https://github.com/Vincit/objection.js/blob/master/examples/express-es7/src/models/Animal.js