How to represent a many-to-many-to-many relationship

Published 2 years ago by alex_hill

I am trying to create what I am calling a many-to-many-to-many relationship for lack of a better phrase to use, and would like to know how to create the third link.

I have a User model and a Book model. When a User borrows a Book from the library a book_user table is updated.

Now I want the User to be able to write some Notes (Note model) on that book (which only the user sees when they are logged in).

The problem I am seeing is that the book_user table is not represented by a model, so I can't do a one-to-many relationship on that.

While the Note is one to many with the Book, it is also one to many with the User, and the combined relationship must be true (ie users cant see each other's notes).

Any tips on representing this would be greatly appreciated.

Thanks

Best Answer (As Selected By alex_hill)
cristian9509

@alex_hill you probably need 4 tables and 4 models. Tables: users, books, book_user, notes, note_user

Models: User, Book, BookUser, Note

You will also need an 'id' for book_user along with book_id and user_id, and in notes table you'll have a book_user_id.

bestmomo
bestmomo
2 years ago (354,110 XP)

Why not add field for note in book_user pivot table ?

alex_hill

Because there may be multiple notes from the same user on the same book.

bestmomo
bestmomo
2 years ago (354,110 XP)

You can create a model for book_user table and set a hasMany relation between book_user and notes table. You can also set a hasMany relation between users and book_user. So you'll be able to make queries.

alex_hill

So you are suggesting I create something like a BookUser Model based on the linking table between Book and User, and I can use BookUser hasMany Notes... Sounds like it would work, will give it a shot when I get a chance. Thanks very much.

cristian9509

@alex_hill you probably need 4 tables and 4 models. Tables: users, books, book_user, notes, note_user

Models: User, Book, BookUser, Note

You will also need an 'id' for book_user along with book_id and user_id, and in notes table you'll have a book_user_id.

alex_hill

Your suggestion worked a charm. I have:

User - users table

Book - books table

UserBook - book_user table

Note - notes table

With a bookuser_note table linking though all the notes. Thanks for the help.

Please sign in or create an account to participate in this conversation.