【问题标题】:how to join 3 tables in laravel using eloquent hasmanythrough or hasonethrough如何使用 eloquent hasmanythrough 或 hasonethrough 在 laravel 中加入 3 个表
【发布时间】:2022-01-10 20:28:06
【问题描述】:

这是我的桌子的样子

departments course subjects
id id id
head department_id course_id
course_name subject_code

在我的模型中,我就是这样做的,但似乎不起作用,我不知道为什么:

public function departments()
{
    return $this->hasOneThrough(
        subjectlist::class,
        department::class,
        'id',
        'course_id',
        'id',
        'id'
    );
}

我尝试使用hasOneThrough时的输出:

{
    "id": 1,
    "department_name": "Business",
    "head": "John smith",
    "email": "smith@gmail.com",
    "contact_number": "09300282103",
    "created_at": null,
    "updated_at": null,
    "subject_list": {
        "id": 1,
        "course_id": 1,
        "subject_code": "Math1",
        "description": "math test",
        "year_type": 1,
        "price": "200.00",
        "units": "5.00",
        "created_at": null,
        "updated_at": null,
        "laravel_through_key": 1
    }
}

我不希望输出应该是这样的,请帮助我如何做到这一点:

{
    "id": 1,
    "department_name": "Business",
    "head": "John smith",
    "email": "smith@gmail.com",
    "contact_number": "09300282103",
    "created_at": null,
    "updated_at": null,
    "subject_list": {
        "id": 1,
        "course_id": 1,
        "subject_code": "Math1",
        "description": "math test",
        "year_type": 1,
        "price": "200.00",
        "units": "5.00",
        "created_at": null,
        "updated_at": null,
        "laravel_through_key": 1
    },
    "department": {
        "id": 1,
        "department_name": "ComputerScience"
    }
}

【问题讨论】:

  • 请出示您的型号查询码。

标签: javascript php laravel model relationship


【解决方案1】:

你的表之间的关系就像 作为课程的主题 课程有一个部门 和科目通过课程有一个部门

主题模型的关系

public function Course() {
    return $this->belongsTo(Course::class);
}
public function Department() {
    return $this->hasOneThrough(Department::class, Course::class)
}

课程模型的关系

public function Subject() {
    return $this->hasMany(Subject::class);
}
public function Department() {
    return $this->belongsTo(Department::class);
}

与您的部门模型的关系

public function Course() {
    return $this->hasMany(Course::class);
}

更多信息请参考 laravel eloquent 关系文档 https://laravel.com/docs/8.x/eloquent-relationships#has-one-through

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-03
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多