如何在Objection.js中定义和使用相关模型

问题描述 投票:0回答:1

使用以下代码(which uses ES6's中的"type":"module" package.json),我似乎无法访问相关的模型Group

import db from "../connection.js";

import objection from "objection";
const { Model } = objection;


Model.knex(db);

class User extends Model {
  static get tableName() {
    return "users";
  }

  static get relationMappings() {
    return {
      groups: {
        relation: Model.ManyToManyRelation,
        modelClass: Group,
        join: {
          from: "users.id",
          through: {
            from: "users_groups.user_id",
            to: "users_groups.group_id",
          },
          to: "groups.id",
        }
      }
    }
  }
}

class Group extends Model {
  static get tableName() {
    return "groups";
  }
}

如果我跑步

const myUser = await User.query().findById(1)

它输出:

用户{id:1,名称:“ r”,电子邮件:“ [email protected]”,用户名:“ raj”,…}

但是我仍然无法访问Group关系:

myUser.groups

输出:

未定义

我在做什么错?

javascript node.js ecmascript-6 knex.js objection.js
1个回答
1
投票

您必须在查询中使用紧急加载来加载所需的关系。

您正在使用Objection.js v1

const myUser = await User.query().eager('groups').findById(1)

并且由于Objection.js v2eager被重命名为withGraphFetched

withGraphFetched

Extra:实例化后加载关系

您可以在实例化后使用const myUser = await User.query().withGraphFetched('groups').findById(1) 加载关系。请注意,所有实例方法均以$relatedQuery开头:

$
© www.soinside.com 2019 - 2024. All rights reserved.