SlintORM
Docsnpm

@polymorphicType / @polymorphicId

Declares polymorphic associations — a single model that can belong to multiple other models. Common patterns: comments on posts or users, images on products or reviews, likes on any content.

Syntax

src/interfaces.ts
interface Comment {
  id: number;
  body: string;
  // @polymorphicType — stores the related model name (e.g. "Post", "User")
  commentableType: string;
  // @polymorphicId — stores the related record's primary key
  commentableId: number;
  createdAt: string;
  updatedAt: string;
}

Usage

src/auth.ts
// Create polymorphic comments
await Comment.insert({
  body: "Great post!",
  commentableType: "Post",
  commentableId: postId,
});
await Comment.insert({
  body: "Nice user!",
  commentableType: "User",
  commentableId: userId,
});

// Resolve the parent — morphTo()
const comment = await Comment.get({ id: 1 });
const parent = await Comment.morphTo();
// Returns the Post or User instance that this comment belongs to

// The morphTo method reads commentableType + commentableId,
// looks up the matching model, and returns the related record.

How It Works

FieldAnnotationPurpose
commentableType@polymorphicTypeStores the model name (e.g. "Post", "User")
commentableId@polymorphicIdStores the related record's primary key value

The schema generator detects both annotations and registers the polymorphic relationship. morphTo() uses the type + id to dynamically resolve the parent model at runtime.

Errors

ErrorCauseFix
Unknown polymorphic type: "X"commentableType value doesn't match any defined modelEnsure the type value matches a model name exactly
Polymorphic id is nullcommentableId is NULL in the databaseAlways provide both type and id together
morphTo() returned nullThe referenced record doesn't exist (deleted or invalid id)Use optional chaining: const parent = await comment.morphTo()

Conventions