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

时间:2019-12-01 02:17:11

标签: laravel laravel-5.8

我正在使用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'));
    }
}

我的观点:views> 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时,它会显示一个学生表数组,但不确定为什么我无法使用first_name之类的字段名称进行遍历。

2 个答案:

答案 0 :(得分:0)

原因是$school->students是数组,没有名为first_name的属性。

您需要

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

答案 1 :(得分:0)

在这种情况下,您要处理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
相关问题