【问题标题】:how to fetch data in 3 tables using with relation in laravel如何在 laravel 中使用与关系获取 3 个表中的数据
【发布时间】:2021-07-27 18:32:07
【问题描述】:

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

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

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

【问题讨论】:

    标签: laravel relation


    【解决方案1】:

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

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

    $student = Student::with(['student_fees', 'admissions', 'admissions.course'])->get();
    

    【讨论】:

      【解决方案2】:
      $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 - 这可以帮助你

      【讨论】:

        猜你喜欢
        • 2020-01-06
        • 2019-03-24
        • 2020-07-20
        • 2020-10-11
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多