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

现在我想在产品模型中建立这种多对多的关系......这可能吗?如何使用这种多对多关系插入 category_restaurants 数据透视表的更新删除?我可以使用 Laravel 在产品模型中使用餐厅和类别表的多对多关系吗?请举例说明

4

1 回答 1

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 ]);
于 2021-05-25T12:15:02.127 回答