Objection.js - Realtion with pivot table

640 Views Asked by At

i'm having hard times understanding how I should model many-to-many relationships in objections.js.

Basically I have an app with an Users, Games and UsersScore tables. A account can have score in game.

Tables are like this:

USERS TABLE

  • id
  • username

GAMES TABLE

  • id
  • name

UsersScore TABLE

  • id
  • userId
  • gameId
  • score

How do I create the relation?

I want to show the logged in user a list of all the games And if he has score in the game then his score

Thanks!!

1

There are 1 best solutions below

0
On

This is essentially identical to the requirements outlined at Join table extra properties in the Objection documentation. You could adapt this to create users, games, and users_games tables. Then your User model might look like this:

class User extends Model {
  static get relationMappings() {
    return {
      relation: Model.ManyToManyRelation,
      modelClass: Game,
      join: {
        from: 'users.id',
        through: {
          from: 'users_games.user_id',
          to: 'users_games.game_id',
          extra: ['score']
        },
        to: 'game.id'
      }
    };
  }
}

Here you can see that we've added an extra score column to our users_games join table. Then I imagine you would get a list of games with something like:

const user = await User.query().findOne({ username: 'wombatsarefluffy' });
const games = await user.$relatedQuery('games');

See the documentation page for an example of how to construct the migrations.