我正在使用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
之类的字段名称进行遍历。
答案 0 :(得分:0)
原因是$school->students
是数组,没有名为first_name
的属性。
您需要
@foreach ($school->students as $student)
{{ $student->first_name }}
@endforeach
答案 1 :(得分:0)
在这种情况下,您要处理2个收藏集:schools
和students
(每个学校),因此您应该使用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