3

I have a database with three tables: users, games and game_user. usersand games have a many to many relationship with game_user as its junction table

The table game_user has only three columns (other than id): game_id, user_id and game_admin.

The idea is that user can be a regular user in a game, or an admin. I would store the values 0 for the former and 1 for the later, for example.

I'm not sure how to do it in Adonis. I have read the documentation and maybe I should create a pivotModel, but I'm not sure how to do it (or IF I should do it for that matter).

I tried the following:

class GameUserSchema extends Schema {
  up () {
    this.create('game_user', (table) => {
      table.increments()
      table.integer('user_id').unsigned().index('user_id')
      table.integer('game_id').unsigned().index('game_id')
      table.integer('game_admin').unsigned().index('game_admin')
      table.foreign('user_id').references('users.id')
                                            .onDelete('cascade')
      table.foreign('game_id').references('games.id')
                                            .onDelete('cascade')
    })
  }

  down () {
    this.drop('game_user')
  }
}

Now when I add games I usually do with the following code:

const newGame = await Game.create(gameData)
await user.games().attach([newGame.id])

But that only updates the junction table with user_id, obviously, not with the user's role.

So my question is: Is my migration file correct or is there a better way? Also how can I update the junction table when creating a game?

pharaohlxvi
  • 73
  • 1
  • 11
  • Pivot-table tag is for transposing rows to columns, not an alias for junction tables. Some ORMs refer to junction tables as pivot tables confusing many developers. Pls read the tag descriptions before using them. – Shadow Jun 01 '18 at 21:26
  • Ok, sorry for that, but I think the tag could be updated, or a new one created, since "Some ORMs refer to junction tables as pivot tables". Just my two cents, but it changes nothing in the question (except some word choices. Thanks for the correction though. – pharaohlxvi Jun 01 '18 at 21:44
  • Or you could ask the people behind your chosen ORM to stop referring to junction tables as pivot tables... The pivot-table tag definition is just fine, adding this reference would confuse users. You managed to find the right tag for your question after being prompted. – Shadow Jun 01 '18 at 22:22

1 Answers1

0

To update the extra attributes of association table you should be using pivot models here is something you can use as a callback to attach method

await user.games().attach(games, (row) => {
   row.game_admin = 1 
})
SBN
  • 123
  • 7
  • One more thing for pivot models the schema would have to be changed, the table name would become game_users in this case – SBN Oct 29 '19 at 12:06