Skip to content

MorphOne Relationship ​

The MorphOne relationship represents a one-to-one polymorphic relationship where a parent model (e.g., Post, Video) can have a single related child record (e.g., Image), 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 one Image. Each Image stores imageable_type (e.g., 'post' or 'video') and imageable_id (the parent id):

In this setup, a Post or Video can have one Image, and the same Image table can be used for both.

Defining the Relationship ​

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

typescript
relationships: {
  image: [MorphOne, 'image', 'imageable_id', 'imageable_type']
}
  • The first argument is the child table name ('image').
  • The second is the foreign key on the child ('imageable_id').
  • The third is the type key on the child ('imageable_type').

Example ​

typescript
{
  models: {
    post: {
      schema: '++id,title',
      properties: ['id', 'title'],
      primaryKey: 'id',
      relationships: {
        image: [MorphOne, 'image', 'imageable_id', 'imageable_type'],
      },
    },
    video: {
      schema: '++id,url',
      properties: ['id', 'url'],
      primaryKey: 'id',
      relationships: {
        image: [MorphOne, 'image', 'imageable_id', 'imageable_type'],
      },
    },
    image: {
      schema: '++id,url,imageable_id,imageable_type',
      properties: ['id', 'url', 'imageable_id', 'imageable_type'],
      primaryKey: 'id',
      relationships: {},
    },
  }
}

Note

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