FG
๐Ÿ—„๏ธ Databases

[FEATURE]: Support Polymorphic Association

Freshabout 20 hours ago
Mar 14, 20260 views
Confidence Score95%
95%

Problem

Describe what you want I'm looking for a Typesafe ORM that support for polymorphic associations. To give a concrete example: I have a `Comment` model. I need this model to be associated with both `Article` and `Photo` models. Instead of creating separate tables or associations for comments on articles and comments on photos, I would prefer a unified approach where a single `Comment` can belong to either an `Article` or a `Photo`. Most ORMs (and query builders) except Prisma support polymorphic association. Prisma is not taking interest in solving this issue: https://github.com/prisma/prisma/issues/1644. If you plan on implementing Prisma, that would be a killer feature that would be a reason in itself to use Drizzle. A few teams have mentioned it explicitly in that issue. Do you plan to support and document this feature in the near future ?

Unverified for your environment

Select your OS to check compatibility.

2 Fixes

Canonical Fix
Unverified Fix
New Fix โ€“ Awaiting Verification

Implement Polymorphic Association for Comments in Drizzle ORM

Medium Risk

Drizzle ORM currently lacks support for polymorphic associations, which prevents a unified approach for models like Comment that need to associate with multiple other models (e.g., Article and Photo). This limitation arises from the absence of a flexible schema design that can accommodate multiple foreign key references in a single table.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Define Polymorphic Association Schema

    Modify the Comment model to include a 'commentable_type' field that indicates the type of associated model (Article or Photo) and a 'commentable_id' field for the associated model's ID.

    typescript
    const Comment = { id: Number, content: String, commentable_id: Number, commentable_type: String };
  2. 2

    Update Database Migration

    Create a migration script to add the new fields to the existing Comments table. Ensure that the new fields are indexed for performance.

    sql
    ALTER TABLE comments ADD COLUMN commentable_id INT, ADD COLUMN commentable_type VARCHAR(255);
  3. 3

    Implement Association Logic

    Create methods in the Comment model to handle the association logic. These methods should allow for saving and retrieving comments based on the associated model type and ID.

    typescript
    function associateComment(comment, commentable) { comment.commentable_id = commentable.id; comment.commentable_type = commentable.constructor.name; }
  4. 4

    Update Query Logic

    Modify the query logic to retrieve comments based on the polymorphic association. This should include filtering by 'commentable_type' and 'commentable_id'.

    typescript
    const comments = await db.comments.find({ where: { commentable_id: articleId, commentable_type: 'Article' } });
  5. 5

    Document Usage

    Update the documentation to include examples of how to use the new polymorphic association feature, including creating, retrieving, and deleting comments.

    typescript
    // Example usage: const comment = new Comment({ content: 'Great article!', commentable_id: article.id, commentable_type: 'Article' });

Validation

To confirm the fix worked, create comments associated with both Article and Photo models and verify that they can be retrieved correctly using the new polymorphic query logic. Ensure that the comments are stored with the correct 'commentable_type' and 'commentable_id'.

Sign in to verify this fix

1 low-confidence fix
Unverified Fix
New Fix โ€“ Awaiting Verification

Implement Polymorphic Associations in Drizzle ORM

Medium Risk

Drizzle ORM currently lacks support for polymorphic associations, which prevents a single Comment model from being associated with multiple models like Article and Photo without creating separate tables or associations. This limitation arises from the design of the ORM, which does not accommodate dynamic relationships between models.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Define Polymorphic Association Structure

    Create a unified Comment model that includes a 'commentable_type' and 'commentable_id' to identify the associated model and its instance.

    typescript
    const Comment = { id: Number, content: String, commentable_type: String, commentable_id: Number };
  2. 2

    Update Article and Photo Models

    Ensure that both Article and Photo models can be referenced by the Comment model through the polymorphic association. This can be done by adding a method to retrieve comments based on the type and ID.

    typescript
    function getComments(commentableType, commentableId) { return comments.filter(comment => comment.commentable_type === commentableType && comment.commentable_id === commentableId); }
  3. 3

    Implement Comment Creation Logic

    Modify the logic for creating comments to accept a 'commentable' parameter that defines the type of model (Article or Photo) and its ID, ensuring the correct values are stored in the Comment model.

    typescript
    function createComment(content, commentableType, commentableId) { const newComment = { id: generateId(), content, commentable_type: commentableType, commentable_id: commentableId }; comments.push(newComment); return newComment; }
  4. 4

    Test Polymorphic Associations

    Develop unit tests to verify that comments can be created and retrieved correctly for both Article and Photo models, ensuring the polymorphic association works as intended.

    typescript
    describe('Polymorphic Associations', () => { it('should retrieve comments for an article', () => { const articleComments = getComments('Article', articleId); expect(articleComments).toBeDefined(); }); });

Validation

Confirm the fix by creating comments for both Article and Photo models and retrieving them using the defined methods. Ensure that the correct comments are returned for each model type and that no errors occur during the process.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

drizzleormtypescriptenhancementrqbimplemented-in-beta