在数据库laravel中查询不同的级别

时间:2017-09-03 13:50:21

标签: database laravel laravel-5 laravel-5.4

美好的一天。我试图查询我的数据库,以获得孩子的孩子。每个用户都有2个孩子。我在使用查询构建器。要求不是使用雄辩和雄辩的关系。但我正在努力。

$firstchild= DB::table('users') - >where('parent_id',  Auth::user() ->id) -> get() ;
$secondchild1 = DB::table('users') - >where('parent_id',  $firstchild[0]->parent_id) ->  get() ;
$secondchild2 = DB::table('users') - >where('parent_id',  $firstchild[1]parent_id) -> get() ;
return view('home' ['firstchild' => $firstchild, 'secondchild1 ' => $secondchild1, 'secondchild2 ' => $secondchild2 , ])

如果用户子节点没有子节点,则返回未定义的偏移量0。如果我想没有任何错误,我该怎么做。

如果我想让这些孩子的孩子得到查询结果,我该怎么做?

1 个答案:

答案 0 :(得分:1)

试试这个:

$firstchild = DB::table('users')->where('parent_id',  Auth::user()->id)->get();

if ($firstchild->count() == 2) {  //**Contains exactly 2 arrays inside the 'firstchild' collection.
    $secondchild1 = DB::table('users')->where('parent_id', $firstchild[0]->parent_id)->get();
    $secondchild2 = DB::table('users')->where('parent_id', $firstchild[1]->parent_id)->get();
}

return view('home', compact('firstchild', 'secondchild1', 'secondchild2'));

希望它有所帮助。