Home > Software engineering >  Laravel models, database and pivot tables question
Laravel models, database and pivot tables question

Time:02-01

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?

CodePudding user response:

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:

return $this->belongsToMany(Book::class)->withPivot('price');

(Adapted from the Laravel documentation, see https://laravel.com/docs/9.x/eloquent-relationships#retrieving-intermediate-table-columns)

CodePudding user response:

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.

public function books()
{
    return $this->belongsToMany(Book::class)
        ->withPivot('price')
}

For example, you are able to access the pivot column in a loop like this

foreach ($shop->books as $book)
{
    echo $book->pivot->price;
}
  • Related