【发布时间】: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 之类的字段名称进行循环。
【问题讨论】:
-
答案中未提及的另一件事是,以这种方式进行查询,您将在循环数据时遇到 n +1 问题。除了使用
all(),您可以使用急切加载来避免它laravel.com/docs/5.8/eloquent-relationships#eager-loading
标签: laravel laravel-5.8