0
Restaurant Table
id ---> PK
Name
Address
City
Phone
Latitude
Longitude
Categories Table
id-->PK
section_id ---> FK
parent_id ---> for categories and sub-categories
category_name-->
slug
categories_restaurants_table
id-> PK
category_id --> FK
restaurant_id --> FK

Now I want to establish this many-to-many relations in the Product Model... Is this possible? How can I insert update delete of categories_restaurants pivot table using this many-to-many relations? Can I use Restaurant and Category Table many to many relation in Product Model using Laravel? Please explain me with example

  • 2
    See docs: [Setup many-to-many relationship](https://laravel.com/docs/8.x/eloquent-relationships#many-to-many) and [Updating many-to-many relationships](https://laravel.com/docs/8.x/eloquent-relationships#updating-many-to-many-relationships) – shaedrich May 25 '21 at 10:20

1 Answers1

0
namespace App\Models;

class Restaurant extends Model
{
    public function categories()
    {
        return $this->belongsToMany(App\Models\Category::class);
    }
}
namespace App\Models;

class Category extends Model
{
    public function restaurants()
    {
        return $this->belongsToMany(App\Models\Restaurant::class);
    }
}
$restaurant = App\Models\Restaurant::find(1);
dd($restaurant->categories);

$categoryA = App\Models\Category::find(1);
$categoryB = App\Models\Category::find(2);
dd($categoryA->restaurants);

$restaurant->attach($categoryA);
$restaurant->dettach($categoryB);

$restaurant->sync([ 1, 2, 4 ]);
shaedrich
  • 5,457
  • 3
  • 26
  • 42
  • Why you use dettach for $categoryB? Actually, I have maintained all categories and subcategories in one single table using parent_id. can i use only single sync function except both attach and dettach function? how can I use this relation in Product Model? – Hit4Development May 26 '21 at 06:21
  • Sure. Sync is just a shorthand for attach/detach. I just wanted to list all possibilities so you can choose from them what suits your use case best. – shaedrich May 26 '21 at 07:27
  • Restaurant Table id ---> PK Name Address City Phone Latitude Longitude Categories Table id-->PK section_id ---> FK parent_id ---> for categories and sub-categories category_name--> slug categories_restaurants_table id-> PK category_id --> FK restaurant_id --> FK these are the possibilites. – Hit4Development May 26 '21 at 11:52
  • I'm not sure, what your problem is. Isn't `sync()` already what you were looking for? – shaedrich May 26 '21 at 12:04