【问题标题】:Laravel lumen get data from another relationLaravel lumen 从另一个关系中获取数据
【发布时间】:2019-03-06 05:13:46
【问题描述】:

我有 3 张桌子 facultiesstudentsprogram_studies。我正在使用 Lumen 5.7

这是表格:

院系表:

-----------------
|id|faculty_name|
-----------------
| 1| test       |
-----------------

学生桌:

----------------------------------
|id|student_name|program_study_id|
----------------------------------
| 1| student 1  |               1|
----------------------------------
| 2| student 2  |               1|
----------------------------------

program_studies 表:

----------------------------------
|id|program_study_name|faculty_id|
----------------------------------
| 1| program study    |         1|
----------------------------------

这是模型:

学生.php

public function programStudy()
{
    return $this->belongsTo(ProgramStudy::class);
}

PorgramStudy.php

public function faculty()
{
    return $this->belongsTo(Faculty::class);
}

Faculty.php

nothing relation in faculty model

如何在学生模型中获取具有关系的教师数据?

现在我在 Student.php 中创建这样的函数:

public function getFaculty()
{
    return $this->programStudy()->first()->faculty()->first();
}

但如果可能的话,我想使用关系而不是函数来获取教师数据

【问题讨论】:

    标签: laravel lumen


    【解决方案1】:

    您可以使用hasOneThrough 关系将您的学生链接到教员。

    public function faculty()
    {
        return $this->hasOneThrough(Faculty::class, ProgramStudy::class);
    }
    

    【讨论】:

    • 我已经尝试过使用 hasOneThrough 但如果我在 StudentController 中调用 dd($student->faculty); 会收到此错误 dd($student->faculty);
    • 您的 Student 模型是否实际上扩展了 Illuminate\Database\Eloquent\Model,或者您使用的是旧版本的 Laravel?
    • 我已经添加了 use Illuminate\Database\Eloquent\Model; ,我正在使用 Lumen 5.7
    • 道歉 - 看起来 hasOneThrough 是在 Laravel 5.8 中引入的。如果可能,您可能希望更新您的 Lumen 安装。
    猜你喜欢
    • 2023-03-10
    • 2020-07-01
    • 2018-02-14
    • 2021-08-06
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多