MorphTo Relationship
The MorphTo relationship represents the inverse of a polymorphic relationship, where the current (child) model stores the type and ID of the related parent model.
Explanation
For example, a Comment or Image might belong to either a Post or a Video as its parent. The child stores *_type
and *_id
fields:
Defining the Relationship
Define MorphTo on the child, specifying the type and id keys:
typescript
relationships: {
parent: [MorphTo, 'commentable_type', 'commentable_id']
}
- The first argument is the type key on the child (e.g., 'commentable_type').
- The second is the id key on the child (e.g., 'commentable_id').
Example
typescript
{
models: {
comment: {
schema: '++id,body,commentable_id,commentable_type',
properties: ['id', 'body', 'commentable_id', 'commentable_type'],
primaryKey: 'id',
relationships: {
parent: [MorphTo, 'commentable_type', 'commentable_id'],
},
},
image: {
schema: '++id,url,imageable_id,imageable_type',
properties: ['id', 'url', 'imageable_id', 'imageable_type'],
primaryKey: 'id',
relationships: {
parent: [MorphTo, 'imageable_type', 'imageable_id'],
},
},
post: {
schema: '++id,title',
properties: ['id', 'title'],
primaryKey: 'id',
relationships: {},
},
video: {
schema: '++id,url',
properties: ['id', 'url'],
primaryKey: 'id',
relationships: {},
},
}
}
Note
MorphTo is used on the child model to point to a parent of varying type, using the type and id keys stored on the child.