I have a database with three tables: users
, games
and game_user
. users
and 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?