通过laravel belongsToMany获取带有数据透视表的记录


fetch records with its pivot table by laravel belongsToMany

我有类别和菜单表。每个菜单都有许多类别并且每个类别都有许多菜单。我有一个category_menu数据透视表,现在我想获取所有菜单记录及其类别,诸如此类的东西。

型号:

class menu extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App'Category');
    }
}

控制器:

class homeController extends Controller
{
    public function __construct(Menu $menu, Category $category)
    {
        $this->menu     = $menu;
        $this->category = $category;
    }
    public function index()
    {
        $data['categories'] = $this->category->all();
        $data['menus']      = $this->menu->all()->categories;
        return view('home', $data);
    }
}

实际上我是幸运地得到了答案是

$this->menu->with('categories')->get();

任何人进入这个问题