通过 laravel belongsToMany 获取其枢轴 table 的记录

fetch records with its pivot table by laravel belongsToMany

我有类别和菜单 table。 每个菜单都有很多类别 每个类别都有很多菜单。 我有一个 category_menu 枢轴 table,现在 我想获取所有菜单记录及其类别之类的东西。

型号:

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();

任何遇到这个问题的人