Laravel Pivot table working with Eloquent ORM
Here is the pivot table. Will make relation with laravel eloquent.
shops
– id
– name
products
– id
– name
product_shop
– product_id
– shop_id
product_shop is called a “pivot” table. Lets make a relation between shops table and products table with this product_shop pivot table.
Here is some rules to follow so that laravel relation need to work.
- Name of the pivot table should consist of singular names of both tables, separated by undescore symbole and these names should be arranged in alphabetical order, so we have to have product_shop, not shop_product.
- To create a pivot table we can create a simple migration with artisan make:migration or use Jeffrey Way’s package Laravel 5 Generators Extended where we have a command artisan make:migration:pivot.
- Pivot table fields: by default, there should be only two fields – foreign key to each of the tables, in our case product_id and shop_id. You can add more fields if you want, then you need to add them to relationship assignment – we will discuss that later.
Models for Many-to-Many Relationships: BelongsToMany
Ok, we have DB tables and migrations, now let’s create models for them. The main part here is to assign a many-to-many relationship – it can be done from either of “main” tables models.
So, option 1:
app/Shop.php:
class Shop extends Model
{
/**
* The products that belong to the shop.
*/
public function products()
{
return $this->belongsToMany('App\Product');
}
}
Actually, you can do both – it depends on how will you actuall use the relationship in other parts of the code: will you need $shop->products or more likely to query $product->shops, or both.
Now, with such declaration of relationships Laravel “assumes” that pivot table name obeys the rules and is product_shop. But, if it’s actually different (for example, it’s plural), you can provide it as a second parameter:
public function products()
{
return $this->belongsToMany('App\Product', 'products_shops');
}
Moreover, you can specify the actual field names of that pivot table, if they are different than default product_id and shop_id. Then just add two more parameters – first, the current model field, and then the field of the model being joined:
public function products()
{
return $this->belongsToMany('App\Product', 'products_shops',
'shops_id', 'products_id');
}
One of the main benefits here: you don’t need to create a separate model for ProductShop – you will be able to manage that table through pivot commands
Reference url: https://laraveldaily.com/pivot-tables-and-many-to-many-relationships/
