Rashomon
Rashomon

Reputation: 6762

Many-to-Many-to-Many relationship in Objection.js

I have a project where an user can have many platforms. These platforms can have many passwords. Currently I have following database structure:

enter image description here

Im trying to use eager loading to get the following object:

{
    "id": 1,
    "username": "Keith",
    "platforms": [
        {
            "id": 1,
            "name": "Jira",
            "passwords": [
                {
                    "id": 1,
                    "password": "hash"
                },
                {
                    "id": 2,
                    "password": "otherhash"
                }
            ]
        },
        {
            "id": 2,
            "name": "Confluence",
            "passwords": [
                {
                    "id": 3,
                    "password": "anotherhash"
                },
                {
                    "id": 4,
                    "password": "anotherone"
                }
            ]
        }
    ]
}

I spent a few hours and couldnt figure out. How could I define the relations to get this structure? Is this possible?

Upvotes: 4

Views: 5184

Answers (1)

Mikael Lepistö
Mikael Lepistö

Reputation: 19718

As far as I know that is not possible to do without creating own model for that 3-way join table.

So models would look something like this:

class User extends objection.Model {
  static get tableName() {
    return 'user';
  }

  static get relationMappings() { 
    return {
      platformPasswords: {
        relation: Model.HasManyRelation,
        modelClass: UserPlatformPassword,
        join: {
          from: 'user.id',
          to: 'user_platform_password.user_id'
        }
      }
    }
  }
}

class Platform extends objection.Model {
  static get tableName() {
    return 'platform';
  }
}

class Password extends objection.Model {
  static get tableName() {
    return 'password';
  }
}

class UserPlatformPassword extends objection.Model {
  static get tableName() {
    return 'user_platform_password';
  }

  static get relationMappings() { 
    return {
      password: {
        relation: Model.HasOne,
        modelClass: Password,
        join: {
          from: 'user_platform_password.password_id',
          to: 'password.id'
        }
      },
      platform: {
        relation: Model.HasOne,
        modelClass: Platform,
        join: {
          from: 'user_platform_password.platform_id',
          to: 'platform.id'
        }
      }
    }
  }
}

Maybe there are some other ways to model those relations at least in a way that they work when doing eager selects, but I'm having hard time to understand how it could work in case when you would like to insert / upsert that nested data, where multiple relations are dealing with different fields of the same join table.

Upvotes: 2

Related Questions