PivotModel does not get called on attach callback


#1

Hi,

These are my models:

'use strict'

const Model = use('Model')

class Plugin extends Model {

/**
 * Displays relationship
 * @return {Object} The Adonis ORM relationship
 */
displays() {
    return this
      .belongsToMany('App/Models/Display')
      .pivotModel('App/Models/DisplayPlugin')
  }

}

module.exports = Plugin


'use strict'

const Model = use('Model')

class Display extends Model {

    /**
     * Plugins relationship
     * @return {Object} The Adonis ORM relationship
     */
    plugins() {
      return this
        .belongsToMany('App/Models/Plugin')
        .pivotModel('App/Models/DisplayPlugin')
    }
}

module.exports = Display

'use strict'

const Model = use('Model')

class DisplayPlugin extends Model {

  static get table () {
    return 'display_plugins'
  }

  display() {
    return this.belongsTo('App/Models/Display');
  }

  plugin() {
    return this.belongsTo('App/Models/Plugin');
  }

  static get primaryKey() {
    return null;
  }

  static get incrementing() {
    return false;
  }

  static get createdAtColumn() {
    return undefined;
  }

  static get updatedAtColumn() {
    return undefined;
  }

}

module.exports = DisplayPlugin

Now when I try to…

let defaultDisplay = await Display.query().where('title', 'Display').first();
let pluginA = await Plugin.query().where('name', 'PluginA').first();
await defaultDisplay.plugins().attach([pluginA.id], (row) => {
    console.log(row)
    row.active = true;
    row.config = ''
});

The attach callback is not called as it says in the docs.

Am I doing something wrong?

Thanks!


#2

More info…

I discovered that I have an hook (afterCreate) in Display model and when I disable the hook, the attach callback gets called… seems weird.

Any ideas?


#3

Ok found the problem.

I thought that I could update with attach but no… attach will not call the callback if the model is already attached.

So, to do the update, this worked for me:

let pluginA = await Plugin.query().where('name', 'PluginA').first();
await defaultDisplay.plugins()
  .pivotQuery()
  .where('plugin_id', pluginA.id)
  .update({
       active: true,
       config: ''
  });

#4

Yes, the attach operation is to insert a new row and updating is the way to go