Hello I am working with Laravel,
I have to create two simple models, let’s say Stores and Books.
Stores can have one or multiple Books and Books can belong to many Stores.
Of course I will use a many to many relationship, with a pivot table.
Books the can have different prices depending the store.
I think a separate table can only complicate things, in my mind the pivot table associating books and stores should have a price column, but pivot tables only contains store_id and book_id.
Should I create a book_prices and associate it with books and to stores? What is the best approach?
3
Answers
You can define additional columns for your pivot table in the migration for the pivot table, and then when defining the relationship use
withPivot
to define the additional columns so they come through in the model:(Adapted from the Laravel documentation, see https://laravel.com/docs/9.x/eloquent-relationships#retrieving-intermediate-table-columns)
You are free and able to set other attributes on your pivot table. You can read more about it in the docs.
https://laravel.com/docs/9.x/eloquent-relationships#retrieving-intermediate-table-columns
You have to define the relationship accordingly, the following should clarify how this works. In this example you use the many-to-many relationship and add the price column to every retrieved pivot model.
For example, you are able to access the pivot column in a loop like this
Depends on the complexity of your case, but yes, you have two options for it. Let’s say that the pivot table is called as
book_store
:Directly adds
price
column tobook_store
. This is obviously the simpler option. The drawbacks are:price
will directly change the price of the relatedbook_store
record. Meaning that a price is being updated "live" e.g users cannot update the price now but "publish" it some time later just like this example in the doc.Create a new, different table to store the price. This may seems relatively more complex, but it may also be more future-proof.
book_store
being a pivot table. One way to see it is like this:book_store
IS a pivot table frombooks
andstores
tables viewpoints, but it’s also just a normal SQL table which could relate to any other tables using any kind of relationships.book_store
table.Alast, it all depends on what you need. Feel free to ask if you need more insight about this. I hope this helps.