我在嘗試更新user
和user_profile
之間的關係。我可以更新的用戶,但我不斷收到這個錯誤,當我嘗試更新user_profile
:ObjectionJS relationship modelClass is not defined
ERROR: Error: UserProfile.relationMappings.user: modelClass is not defined
至於我可以告訴我模仿從文檔的例子,打字稿的例子,但任何人都可以看到爲什麼這不起作用?
我包含查詢,兩種模型和用戶配置文件遷移。 BaseModel的內容被註釋掉,因此它等同於直接從Model繼承,jsonSchema
僅用於驗證,因此爲了簡潔起見將其刪除。
UPDATE
卸下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);
});
};
感謝您的回覆,以打字稿模塊不能有循環依賴關係,但我沒有嘗試這個以防萬一: )似乎與用戶配置文件 – mtpultz
是特別關係是的,所以我的意思,而是導入用戶在UserProfile模塊中定義modelClass作爲模塊的路徑:)我認爲這應該有所幫助 - 這裏是TS中的示例 - 看看modelClass業主關係 – DonCziken
謝謝你是完全正確的。錯誤沒有描述問題很有趣。我從來沒有根據錯誤計算出來。最終的解決方案是'$ {__ dirname}/user.model',並且對於'user-profile.model'也是一樣的,以防萬一任何人想要確切地知道工作的代碼。 – mtpultz