sequelize / sequelize

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.
https://sequelize.org/
MIT License
29.42k stars 4.26k forks source link

Support for a n:m table where both are polymorphic #10854

Open amayer1 opened 5 years ago

amayer1 commented 5 years ago

Is your feature request related to a problem? Please describe.

The sequelize functions don't work well with a n:m table where both sides to it are polymorphic.

For example, let's extend the example given in the docs here: http://docs.sequelizejs.com/manual/associations.html#n-m

Let's say that we don't only have 'tags' but we also have 'comments'. So, the current situation is that a post/image can have many tags/comments and vice versa and we want a joint table to represent that. Now both pieces are polymorphic, which is different from in the example.

The issue now is that say I want to associate an image instance with a list of tags already in the tags table:

imageInstance.addTags(tagIds);

When inserting into the join table, it won't grab the the column/scope defined in the Tags table. The SQL generated looks like: INSERT INTO <jointTableName> (postOrImage, postOrImageId, tagOrCommentId) VALUES...

Describe the solution you'd like

The above should do: INSERT INTO <jointTableName> (postOrImage, postOrImageId, _tagOrComment_, tagOrCommentId) VALUES...

A workaround that worked was working was:

imageInstance.addTags(tagIds, _{ through: {tagOrComment: 'tags' }}_);

But that came with another issue - Mainly that the 'check' Sequelize does before inserting into a joint table to ensure it's unique, also does not check the tagOrComment column, so if I then ran this command:

imageInstance.addComments(commentIds, _{ through: {tagOrComment: comments }}_);

It would just check if the 'postOrImage', 'postOrImageId', and 'tagOrCommentId' are unique and not the 'tagOrComment'. This is an issue if the tag/comment share an ID, because if they did, it performs an update thinking it's the same record.

Why should this be in Sequelize

Because it's pretty natural.

github-actions[bot] commented 2 years ago

This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the "stale" label. 🙂