adonis4-lucid-polymorphic
v0.1.0
Published
Adonis 4.x Lucid Polymorphic Relations Support.
Downloads
5
Maintainers
Readme
Adonis Lucid Polymorphic
Polymorphic Relations support for Adonis 4.x Lucid.
Installation
- Add package:
$ npm i adonis4-lucid-polymorphic --save
or
$ yarn add adonis4-lucid-polymorphic
- 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.