0

Using the following code (which uses ES6's "type":"module" in package.json), I can't seem to access the related Model 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";
  }
}

If I run

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

It outputs:

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

But I still can't access the Group relation:

myUser.groups

Outputs:

undefined

What am I doing wrong?

Raj
  • 1,555
  • 18
  • 32

1 Answers1

2

You have to use eager loading in the query to load the desired relations.

It you are using Objection.js v1:

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

And since Objection.js v2, eager was renamed as withGraphFetched:

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

Extra: Loading relations after instantiation

You can load the relations after instantiation using $relatedQuery. Note all instance methods starts with $:

const myUser = await User.query().findById(1)
const groupsOfMyUser = await myUser.$relatedQuery('groups')
Rashomon
  • 5,962
  • 4
  • 29
  • 67
  • 1
    Thank you very much! Can `.withGraphFetched()` (or some rendition of it) be used on an an instance? For example if `myUser` was already queried without `.withGraphFetched('groups')`, can it be done after instantiation? – Raj Apr 28 '20 at 19:35
  • Yep, added to the answer :) – Rashomon Apr 29 '20 at 06:13