Has many through and has and belongs to many are substitutes

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.

Last Updated: 2024-11-21

I was having an issue with a hasManyThrough relationship code in an ORM - I could not get my user to have many slots through tickets using their library.

Basically I had: - a User object - a (time) Slot object - a Ticket object with userid and slotid (i.e. a User has many tickets and a Slot also has many tickets)

A user has_many tickets - no problem. But I could not get a user to have many slots THROUGH tickets.

I got unstuck upon realizing a hasManyThrough can be done as a hasAndBelongsToMany relationship, with the intermediary (ticket) being the join table. Luckily for me, the ORM code worked in this branch.

How exactly do I know this? Well consider how the following shows a pivot table embedded inside the tickets data.

ticket id=1 (slot_id=1, user_id=1) price=12.00
ticket id=1 (slot_id=1, user_id=2) pirce=14.00