belongsToMany relation failed with E_CANNOT_OVERRIDE_RELATION during seed


#1

Hi all,

sorry if my question has no sense but I don’t find any answers on this forum or by google search.

I have 2 tables, one for Users (classic one) and the other one a pivot table to describe followers. The migration file for this one is :

const Schema = use('Schema')

class FollowersSchema extends Schema {
  up () {
    this.create('followers', (table) => {
      table.integer('user_id').unsigned().index().notNullable().references('id').inTable('users').onDelete('cascade')
      table.integer('follower_id').unsigned().index().notNullable().references('id').inTable('users').onDelete('cascade')
      table.primary(['user_id', 'follower_id'])
      table.timestamps()
    })
  }
  
  down () {
    this.drop('followers')
  }
}

I declare belongsToMany relations in my User model, one for having followers and this other one to have followings :

class User extends Model {
  followers() {
    return this.belongsToMany('App/Models/User', 'user_id', 'follower_id')
      .pivotTable('followers')
      .withTimestamps()
  }
  
  followings() {
    return this.belongsToMany('App/Models/User', 'follower_id', 'user_id')
      .pivotTable('followers')
      .withTimestamps()
  }
}

I try to make a seeder to have a set of test data. My seeder file looks like:

class TestUserSeeder {
  async run () {
    
    // 'TestUser' creation
    const testUser = await Factory
      .model('App/Models/User')
      .create({ username: 'test', email: 'test@test.com', password: 'test' })
    
    // Other users
    const otherUsers = await Factory
      .model('App/Models/User')
      .createMany(10, { password: 'test' })

    // Adding some followers
    await testUser.followings().saveMany([otherUsers[0], otherUsers[1], otherUsers[2]])
    await testUser.followers().saveMany([otherUsers[9], otherUsers[8], otherUsers[2]])
  }
}

If I comment the second line (testUser.followers…), all is right !
But if I let the two lines, data in my database are right (i have my 6 new lines in followers table), but I have a runtime error :

RuntimeException: E_CANNOT_OVERRIDE_RELATION: Trying to eagerload pivot relationship twice
> More details: https://err.sh/adonisjs/errors/E_CANNOT_OVERRIDE_RELATION

Can you have an idea to solve this error ? I’m a new user of Adonis so, I certainly make a mistake somewhere…

Thanks !


#2

I know the problem is with re-using the instance of otherUsers[2], which is causing this issue.

Ideally it’s a bug and I will look into it.

Can you do one thing, is create an issue with https://github.com/adonisjs/adonis-lucid repo and leave a reference to this thread?


#3

Indeed, removing otherUsers[2] solved the problem.

Thanks for your answer.

I report the issue on Adonis Lucid github.