Skip to content

MorphMany Relationship

The MorphMany relationship represents a one-to-many polymorphic relationship where a parent model (e.g., Post, Video) can have many related child records (e.g., Comment), and those children can belong to different parent types. The polymorphic keys are stored on the child table.

Explanation

For example, both a Post and a Video can have many Comments. Each Comment stores commentable_type (e.g., 'post' or 'video') and commentable_id (the parent id):

In this setup, a Post or Video can have many Comments, and the same Comment table can be used for both.

Defining the Relationship

Define MorphMany on the parent, pointing to the child table and specifying the foreign key and type columns:

typescript
relationships: {
  comments: [MorphMany, 'comment', 'commentable_id', 'commentable_type']
}
  • The first argument is the child table name ('comment').
  • The second is the foreign key on the child ('commentable_id').
  • The third is the type key on the child ('commentable_type').

Example

typescript
{
  models: {
    post: {
      schema: '++id,title',
      properties: ['id', 'title'],
      primaryKey: 'id',
      relationships: {
        comments: [MorphMany, 'comment', 'commentable_id', 'commentable_type'],
      },
    },
    video: {
      schema: '++id,url',
      properties: ['id', 'url'],
      primaryKey: 'id',
      relationships: {
        comments: [MorphMany, 'comment', 'commentable_id', 'commentable_type'],
      },
    },
    comment: {
      schema: '++id,body,commentable_id,commentable_type',
      properties: ['id', 'body', 'commentable_id', 'commentable_type'],
      primaryKey: 'id',
      relationships: {},
    },
  }
}

Note

MorphMany is used when a parent can have multiple polymorphic children, and the child table stores the type and id of the parent. If you need only a single child, use MorphOne instead.