2017-10-15 120 views
1

我在嘗試更新useruser_profile之間的關係。我可以更新的用戶,但我不斷收到這個錯誤,當我嘗試更新user_profileObjectionJS relationship modelClass is not defined

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

至於我可以告訴我模仿從文檔的例子,打字稿的例子,但任何人都可以看到爲什麼這不起作用?

我包含查詢,兩種模型和用戶配置文件遷移。 BaseModel的內容被註釋掉,因此它等同於直接從Model繼承,jsonSchema僅用於驗證,因此爲了簡潔起見將其刪除。

UPDATE

卸下relationshipMappingsUserProfile發生停止錯誤,但因爲我需要BelongsToOneRelation關係,我還在努力。至少它似乎被縮小到relationMappingsUserProfile

查詢

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); 
    }); 
}; 

回答

2

我要說的是

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

+0

感謝您的回覆,以打字稿模塊不能有循環依賴關係,但我沒有嘗試這個以防萬一: )似乎與用戶配置文件 – mtpultz

+0

是特別關係是的,所以我的意思,而是導入用戶在UserProfile模塊中定義modelClass作爲模塊的路徑:)我認爲這應該有所幫助 - 這裏是TS中的示例 - 看看modelClass業主關係 – DonCziken

+1

謝謝你是完全正確的。錯誤沒有描述問題很有趣。我從來沒有根據錯誤計算出來。最終的解決方案是'$ {__ dirname}/user.model',並且對於'user-profile.model'也是一樣的,以防萬一任何人想要確切地知道工作的代碼。 – mtpultz

相關問題