【问题标题】:fetch records with its pivot table by laravel belongsToMany通过 laravel belongsToMany 使用其数据透视表获取记录
【发布时间】:2015-12-29 02:17:35
【问题描述】:

我有类别和菜单表。 每个菜单都有很多类别 每个类别都有很多菜单。 我有一个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);
    }
}

【问题讨论】:

  • 你有什么问题?
  • 你能改写一下吗,我不知道你的问题是什么。
  • 我已经得到了答案,谢谢,但我的问题是我想要一个菜单​​列表及其类别表

标签: php laravel pivot


【解决方案1】:

实际上我通过幸运的尝试得到了答案 这是

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

任何人都进入这个问题

【讨论】:

    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2018-06-08
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多