adonis4-lucid-polymorphic

Adonis 4.x Lucid Polymorphic Relations Support.

Usage no npm install needed!

<script type="module">
  import adonis4LucidPolymorphic from 'https://cdn.skypack.dev/adonis4-lucid-polymorphic';
</script>

README

Adonis Lucid Polymorphic

Polymorphic Relations support for Adonis 4.x Lucid.

Installation

  1. Add package:
$ npm i adonis4-lucid-polymorphic --save

or

$ yarn add adonis4-lucid-polymorphic
  1. Register providers inside the your bootstrap/app.js file.
const providers = [
  ...
  'adonis4-lucid-polymorphic/providers/PolymorphicProvider',
  ...
]

Examples

Table Structure

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

Model Structure

// App/Model/Post
'use strict'

const Model = use('Lucid')

class Post extends Model {
  static get traits () {
    return ['@provider:Morphable']
  }

  comments () {
    return this.morphMany('App/Models/Comment', 'commentable', 'id')
  }
}

module.exports = Post
// App/Model/Video
'use strict'

const Model = use('Lucid')

class Video extends Model {
  static get traits () {
    return ['@provider:Morphable']
  }

  comments () {
    return this.morphMany('App/Models/Comment', 'commentable', 'id')
  }
}

module.exports = Video
// App/Model/Comment
'use strict'

const Model = use('Lucid')

class Comment extends Model {
  static get traits () {
    return ['@provider:Morphable']
  }

  commentable () {
    return this.morphTo('commentable', [
      'App/Models/Post', 'App/Models/Video'
    ])
  }
}

module.exports = Video

API

morphTo(determiner, morphMap, [primaryKey])

...

class Comment extends Model {
  static get traits () {
    return ['@provider:Morphable']
  }

  commentable () {
    return this.morphTo('commentable', [
      'App/Models/Post', 'App/Models/Video'
    ], 'id')
  }
}

...

morphMany(relatedModel, determiner, [primaryKey])

...

class Post extends Model {
  static get traits () {
    return ['@provider:Morphable']
  }

  comments () {
    return this.morphMany('App/Models/Comment', 'commentable', 'id')
  }
}

...

morphOne(relatedModel, determiner, [primaryKey])

...

class Publication extends Model {
  static get traits () {
    return ['@provider:Morphable']
  }

  content () {
    return this.morphOne('App/Models/Content', 'contentable', 'id')
  }
}

...

Credits

Support

Having trouble? Open an issue!

License

The MIT License (MIT). Please see License File for more information.