Polymorphic Relations support for Adonis Lucid.
- Add package:
$ npm i adonis-lucid-polymorphic --save
or
$ yarn add adonis-lucid-polymorphic
- Register providers inside the your bootstrap/app.js file.
const providers = [
...
'adonis-lucid-polymorphic/providers/PolymorphicProvider',
...
]
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
// App/Model/Post
'use strict'
const Model = use('Lucid')
class Post extends Model {
static get traits () {
return ['Adonis/Lucid/MorphTrait']
}
comments () {
return this.morphMany('App/Model/Comment', 'commentable')
}
}
module.exports = Post
// App/Model/Video
'use strict'
const Model = use('Lucid')
class Video extends Model {
static get traits () {
return ['Adonis/Lucid/MorphTrait']
}
comments () {
return this.morphMany('App/Model/Comment', 'commentable')
}
}
module.exports = Video
// App/Model/Comment
'use strict'
const Model = use('Lucid')
class Comment extends Model {
static get traits () {
return ['Adonis/Lucid/MorphTrait']
}
commentable () {
return this.morphTo('commentable', [
'App/Model/Post', 'App/Model/Video'
])
}
}
module.exports = Video
...
class Comment extends Model {
static get traits () {
return ['Adonis/Lucid/MorphTrait']
}
commentable () {
return this.morphTo('commentable', [
'App/Model/Post', 'App/Model/Video'
], 'id')
}
}
...
...
class Post extends Model {
static get traits () {
return ['Adonis/Lucid/MorphTrait']
}
comments () {
return this.morphMany('App/Model/Comment', 'commentable', 'id')
}
}
...
...
class Publication extends Model {
static get traits () {
return ['Adonis/Lucid/MorphTrait']
}
content () {
return this.morphOne('App/Model/Content', 'contentable', 'id')
}
}
...
Having trouble? Open an issue!
The MIT License (MIT). Please see License File for more information.