Laravel: 在一对多关系中循环检索数据

Laravel: Retrieving Data in Loop in a One to Many Relationship

我正在使用 Laravel 5.8。这是我的代码...

CreateSchoolsTable 迁移

public function up()
{
    Schema::create('schools', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });
}

CreateStudentsTable 迁移

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('school_id');
        $table->string('first_name');
        $table->timestamps();
    });
}

学校模式

class School extends Model
{
    public function students()
    {
        return $this->hasMany('App\Student');
    }
}

学生模型

class Student extends Model
{
    public function school()
    {
        return $this->belongsTo('App\School');
    }
}

控制器

class SchoolsController extends Controller
{
    public function index()
    {
        $schools = School::all();

        return view('schools.index', compact('schools'));
    }
}

我的观点:观点>学校>index.blade.php

@foreach ($schools as $school)
    {{ $school->students->first_name }}
@endforeach

我想在循环中显示所有名字,$school->students->first_name 给我一个错误。

属性 [first_name] 在此集合实例上不存在。 (查看:/Users/philginsburg/Laravel/project1/resources/views/schools/index.blade.php)

当我回显 $school->students 时,它会显示一个学生数组 table,但不确定为什么我不能使用 first_name.[=20= 这样的字段名称进行循环]

原因是$school->students是数组,没有属性叫first_name

你需要

@foreach ($school->students as $student)
    {{ $student->first_name }}
@endforeach

在这种情况下,您要处理 2 个集合:schoolsstudents(每个学校的),因此您应该使用 2 个不同的循环来遍历这些集合,如下所示:

@foreach ($schools as $school)
    <p>In this school there are those students:</p>
    <ul>
       @foreach($school->students as $student)
           <li>{{ $student->first_name }}</li>
       @endforeach
    </ul>
@endforeach