我如何在 Laravel 控制器的 foreach() 循环中获取数据

How can i fetch data in a foreach() loop in Laravel controller

我在组和学生之间有一个一对多的关系,我想得到一些组的所有学生,所以我这样做:

public function getStudentsOfGroups()
{
    $groups = Auth::user()->groups;
    foreach($groups as $group){
        $students  = $group->students;
    }

    return view('teacher.home', compact('students'));
}

但是它没有得到我需要的数据,那么我能做些什么呢?

试试这个:

$students = Student::whereHas('groups', function (Builder $query) {
    $query->where('your_foreign_key_on_groups', auth()->id());
})
->get();

注意: 当你想向数组中添加一些东西时,你应该使用这个语法:

$array[] = 'a new element';
    public function getStudentsOfGroups()
{
    $groups = Auth::user()->groups;
    foreach($groups as $group){
        $students[]  = $group->students;
    }

    return view('teacher.home', compact('students'));
}

你可以

$results = Auth::user()->groups->students

或者

$results = Group::with('students')->where('user_id', Auth::user()->id;