Degen-IO / pokerbackend

HomeGame | Multiplayer Texas Hold Em Poker for Games with Friends
0 stars 0 forks source link

Polymorphic Associations for Tables #70

Closed patrickbrown-io closed 6 months ago

patrickbrown-io commented 7 months ago

The challenge was in associating the Table model with either a CashGame or a TournamentGame using a single gameId field, which led to ambiguity and the foreign key constraint violation error.

Some reading:

https://codinglollypop.medium.com/polymorphic-association-in-sequelize-with-migration-bc084af2ba78

https://sequelize.org/docs/v6/advanced-association-concepts/polymorphic-associations/


Key Issues:

Foreign Key Constraint Violation: The error message you encountered indicated a foreign key constraint violation. This was likely because the Table model was trying to associate with both CashGame and TournamentGame models using the same gameId field. Relational databases require that a foreign key must reference a primary key in another table. Since gameId could not uniquely identify whether it was referring to a CashGame or TournamentGame, it caused integrity constraints to be violated when the same ID existed in both tables or when referencing an ID that did not exist in the expected table.

Lack of Support for Polymorphic Associations:

Traditional relational databases (and by extension, Sequelize) do not natively support polymorphic associations without custom implementation. Polymorphic associations are a way to associate a model with multiple other models through a single association. Your initial implementation did not clearly define how to manage these polymorphic relationships, leading to confusion and errors when trying to associate tables with different types of games.

Solutions:

Introduction of Polymorphic Fields: By introducing gameableId and gameableType fields to the Table model, you clearly defined the polymorphic association. gameableId holds the ID of the associated game (either a CashGame or TournamentGame), and gameableType indicates the type of game it is associated with. This approach resolves the ambiguity and allows for flexible and clear associations between tables and different types of games.

Adjusting Model Associations:

Adjusting the associations in the CashGame and TournamentGame models to reflect this new polymorphic setup allowed for proper relationship management. This included specifying the scope for the association based on the gameableType field.

Adapting Utility Functions and Business Logic:

Finally, updating your utility functions and any business logic that creates or interacts with these associations ensured that your application correctly handles the creation and querying of tables in relation to their respective games, adhering to the polymorphic design.

patrickbrown-io commented 6 months ago

Resolved via #73