如何在查询构建器中进行自连接 eloquent

How to do self join in query builder no eloquent

很难使用查询构建器进行自连接,但在使用 toSql()get() 时得到意外结果或查询,请不要建议 eloquent,只需使用查询构建器原始查询。

正在尝试让所有子菜单都跟随其父菜单。 还需要 ID 列

$users = DB::table('all_menus as A all_menus as B')
->select(DB::raw('A.menu_name__v1 As menu_name_parent, B.menu_name__v1 As menu_name_child'))
->where('A.id', '=' 'B.parent_menu_id__v1')
->toSql();

join() 方法支持定义别名,因此您可以使用别名自行连接,如下查询:

$users = DB::table('all_menus as A')
           ->join('all_menus as B', 'A.id', '=', 'B.parent_menu_id__v1')
           ->select('A.menu_name__v1 AS menu_name_parent', 'B.menu_name__v1 AS menu_name_child')
           ->toSql();