首页 > 解决方案 > 如何从嵌套关系中获取特定列 - Laravel

问题描述

我有三个表如下

课程表

ID | title     | 
---|-----------|
1  |  course 1 | 

章节章节表

ID | course_id | title             |
---|-----------|-------------------|
1  |       1   | Chapter Section 1 |
2  |       1   | Chapter Section 2 |

章节表

ID | chapter_section_id | title     |
---|--------------------|-----------|
1  |       1            | Chapter 1 |
2  |       2            | Chapter 2 |

我已将关系定义如下。

课程模式

public function chapterSections() {
    return $this->hasMany('App\CHAPTER_SECTION', 'course_id');
}

CHAPTER_SECTION 模型

public function chapterSections() {
    return $this->hasMany('App\CHAPTER_SECTION', 'course_id');
}

现在我只想从章节表中获取标题列。参考laravel 文档这是我的尝试。

COURSE::with('chapterSections.chapters:id,title')->get();

我从课程表和 chapter_sections 表中获取列,但我没有从章节表中接收列,而是得到空数组。

我的邮递员输出

[
    {
        "id": 1,
        "title": "course 1",
        "chapter_sections": [
            {
                "id": 1,
                "course_id": 1,
                "title": "Chapter Section 1",
                "chapters": []
            },
            {
                "id": 2,
                "course_id": 1,
                "title": "Chapter Section 2",
                "chapters": []
            },
        ]
    }
]

我想要的是只获取 id 和标题列章节表。这是我想要的输出。

[
        {
            "id": 1,
            "chapter_section_title": "chapter section 1",
            "title": "chapter 1",
        },
        {
            "id": 1,
            "chapter_section_title": "chapter section 2",
            "title": "chapter 2",
        }
    ]

是否有任何关系方式,或者我必须使用连接来获得上述输出

标签: laraveleloquent-relationship

解决方案


您也可以通过在章节章节上使用 with 来将章节放在章节章节中,就像您在课程中所做的那样。

如果您想让它们与所有响应一起出现,那么您可以在章节章节中声明 $with。

如果您只想让它们用于此响应,那么您可以使用静态方法,就像您在课程中所做的那样。

祝你好运


推荐阅读