Not getting error from BelongsToMany attach() in duplication


#1

Hi.

I have a belongsToMany relationship between users. This relation has a unique index defined based on the two users, so It cannot be a duplication.

migration:

    this.create(users_pivots', (table) => {
      table.increments()
      table.timestamps()
      table.integer('user_id').unsigned().notNullable() // id del usuario que definió la relación.
      table.integer('user_target_id').unsigned().notNullable()
      table.integer('relation_id').unsigned().notNullable()
table.unique(['user_id','user_target_id'])
    })

This unique index is saved in the Database. If I try to duplicate a relation manually with insert() I got the duplication error.

await Database
                    .table('users_pivots')
                    .insert({
                      'user_id': user.id,
                      'user_target:id':  targetUser.id,
                      'relation_id':        linkTypeId                      
                    })

=> got duplication error

But it I duplicate the relation with attach() I don’t get any error nor update.

  await user.linkedFrom().attach(target.id,(row)=>{
      row.relation_id=linkTypeId
})

This will create the relation if it doesn’t exist but won’t throw any error if it exists.

Is it possible to throw the error with attach()?


#2

You probably want to use sync() instead of attach() if you are updating relations and need to ensure non-duplication.