Eloquent relationship with different table name and table fields for belongsToMany using pivot table?


Posted 8 months ago by Ryan Dhungel

Category: Eloquent Laravel

Viewed 490 times

Estimated read time: 1 minute

Course of the day!

Vue Vuex Firebase -  Building Advance Web App (Slack Clone)

Vue Vuex Firebase - Building Advance Web App (Slack Clone)

Solution to belongsToMany relationship with pivot table that has different naming to their table name and column fields.

The standard way:

This example would work if you have named your database table and column fields appropiratelyThis is how it shuold look like inside Product.php

The standard way is alway use singular version of the model name, follow the alphabetical order and use underscore

public function categories()
{
// We have already created pivot table for products and categories
return $this->belongsToMany(Category::class);
}

You have changed your table name

This is how you have to supply table name if you have used different table name

public function categories()
{
return $this->belongsToMany(Category::class, 'products_categories');
}

You have changed your table fields names too

This is how you have to supply table name along with column fields name if you have used different naming convention
The right way would be naming fields as category_id and product_id

public function categories()
{
/** * The order here is Table name comes first then comes local name and foreign name * Table name 'products_categories' * Local name 'prod_id' * Foreign name 'cate_id' */
return $this->belongsToMany(Category::class, 'products_categories', 'prod_id', 'cate_id');
}