2

I was wondering how I can solve a many to many solutions with migrations like at this diagram: DB relation diagram

u_id_user is a FK from the User table

u_g_id is unique and auto-increment

g_id_group is a FK from Group

Code example:

class UserGroupsSchema extends Schema {
  up () {
    this.create('user_groups', (table) => {
      table.increments()
      table.integer('u_id_user')
      table.integer("g_id_group")
      table.timestamps()
    })
  }

An other problem is that if I run my migrations it creates the tables with type MyISAM and I cant build relations with this type.. so how can I change the default type to InnoDB?

  • As a rule of thumb, it's not good to mix your questions, you can also change the storage engine to InnoDB manually as it depends on your database configuration. I haven't found a way to do this from adonis – VladNeacsu Oct 29 '19 at 14:19

1 Answers1

0

From the adonis.js documentation you need to define your models like this:

const Model = use('Model')

class User extends Model {
  groups () {
    return this.belongsToMany('App/Models/Group')
  }
}

module.exports = User

After that you can query the date like this:

const user = await User.find(1)

const groups = await user
  .groups()
  .wherePivot('user_id', '=', user.id)
  .fetch()

I haven't tested the code but this should put you on the right track

VladNeacsu
  • 1,268
  • 16
  • 33