mtp*_*ltz 1 node.js objection.js
我正在尝试更新 auser和之间的关系user_profile。我可以更新用户,但是当我尝试更新以下内容时,我不断收到此错误user_profile:
ERROR: Error: UserProfile.relationMappings.user: modelClass is not defined
据我所知,我已经模仿了文档和 TypeScript 示例中的示例,但是谁能看出为什么这不起作用?
我包括了查询、模型和用户配置文件迁移。BaseModel 的内容被注释掉了,相当于直接从 Model 继承了,并且jsonSchema只用于验证,所以为了简洁起见我把它们去掉了。
更新
删除relationshipMappingsfrom 会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 });
Run Code Online (Sandbox Code Playgroud)
楷模
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'
}
}
};
}
Run Code Online (Sandbox Code Playgroud)
移民
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);
});
};
Run Code Online (Sandbox Code Playgroud)
我会这样说
a) 这是循环依赖的问题或/和 b) 导入路径有问题
一种是在模型类中使用绝对文件路径而不是构造函数。例如
modelClass: __dirname + '/User'
Run Code Online (Sandbox Code Playgroud)
或者
modelClass: require('./User').default
Run Code Online (Sandbox Code Playgroud)
查看示例:https : //github.com/Vincit/objection.js/blob/master/examples/express-es7/src/models/Animal.js
| 归档时间: |
|
| 查看次数: |
1794 次 |
| 最近记录: |