【问题标题】:Laravel: Retrieving Data in Loop in a One to Many RelationshipLaravel:以一对多关系循环检索数据
【发布时间】:2020-03-26 01:37:24
【问题描述】:

我正在使用 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 之类的字段名称进行循环。

【问题讨论】:

标签: laravel laravel-5.8


【解决方案1】:

在这种情况下,您正在处理 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

【讨论】:

    【解决方案2】:

    原因是$school-&gt;students是数组,没有叫first_name的属性。

    你需要

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

    【讨论】:

    • 它是一个集合,而不是一个数组
    猜你喜欢
    • 1970-01-01
    • 2017-01-17
    • 2014-08-11
    • 2014-04-18
    • 2021-04-06
    • 2023-02-07
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多