Ignore failed relations on eager loading

Hi!

I’m trying to implement polymorphic relations on Adonis.js.

I’m using a switch on the model’s polymorphic relationship to know what model belongsTo should point. Here is my Notification model:

class Notification extends Model {

  ....

  entity () {
    switch(this.entity_type) {
      case 'App/Models/Post':
        return this.belongsTo('App/Models/Post', 'entity_id', 'id')
      case 'App/Models/PostComment':
        return this.belongsTo('App/Models/PostComment', 'entity_id', 'id')
    }
  }
}

On my controller, i’ve solved it this way:

class NotificationController {

  async index({ request, auth }) {
    return await auth.user.notifications()
    .with('triggerer')
    .with('entity')
    .paginate(request.get().page, 10)
  }

  ...

}

This works at first, but the problem comes when one of the related rows gets deleted (for example: a user deletes one of his posts that was referenced on a notification). I get the following error:

Cannot destructure property `relatedQuery` of 'undefined' or 'null'.

Is there a way of using with and ignore missing/failed relations? As i’m implementing polymorphic relationships, i cannot use onDelete('cascade').

Thank you very much! ^^

1 Like