如何使用laravel中的关系获取3个表中的数据

问题描述

我想从三个表中获取数据。该表被命名为学生录取和课程。在我的查询中,我使用以下查询获取学生数据和录取数据

$student = Student::with('student_fees')->with('admissions')->get();

而且我也想要课程表数据,但是课程表数据与录取表有关。如何使用此查询获取课程表数据?

解决方法

你可以使用嵌套的预先加载 https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

假设您在每个模型类中定义了与 Laravel 约定的关系。您可以调用嵌套的急切加载,如下所示:

$student = Student::with(['student_fees','admissions','admissions.course'])->get();
,
$users = DB::table('Student')->join('admissions','student.id','=','admissions.student_id')->join('course','course.id','admissions.course_id')->select('Student.*','Student.name','course.name')->get();

https://laravel.com/docs/5.7/queries#joins - 这可以帮助您