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

How to define and use a related Model in Objection.js

使用以下代码(which uses ES6's "type":"module" in 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)

它输出:

User {id: 1, name: "r", email: "raj@raj.raj", username: "raj", … }

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

myUser.groups

输出:

undefined

我做错了什么?

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

你正在使用 Objection.js v1:

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

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

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

Extra: 实例化后加载关系

您可以使用 $relatedQuery 在实例化后加载关系。注意所有实例方法都以 $:

开头
const myUser = await User.query().findById(1)
const groupsOfMyUser = await myUser.$relatedQuery('groups')