如何从嵌套关系中获取特定列-Laravel

如何从嵌套关系中获取特定列-Laravel,laravel,eloquent-relationship,Laravel,Eloquent Relationship,我有三张桌子如下 课程表 ID | title | ---|-----------| 1 | course 1 | ID | course_id | title | ---|-----------|-------------------| 1 | 1 | Chapter Section 1 | 2 | 1 | Chapter Section 2 | ID | chapter_section_id | title

我有三张桌子如下

课程表

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 |
章节章节表

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 |
章节表

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');
}
public function chapterSections() {
    return $this->hasMany('App\CHAPTER_SECTION', 'course_id');
}
章节章节模型

public function chapterSections() {
    return $this->hasMany('App\CHAPTER_SECTION', 'course_id');
}
public function chapterSections() {
    return $this->hasMany('App\CHAPTER_SECTION', 'course_id');
}
现在我只想从chapters表中获取标题列。这是我的尝试

COURSE::with('chapterSections.chapters:id,title')->get();
我从courses表和chapter_sections表中获取列,但不是从chapter表中获取列,而是获取空数组

我的邮差输出

[
    {
        "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和title列。这是我想要的输出

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

是否有任何关联方法可以这样做,或者我必须使用联接来获得上述输出

您可以在章节中使用with,将章节放在章节中,方法与您在课程中使用的方法相同

如果您想让它们包含所有响应,那么您可以在小节章节中声明$with

如果您只想让它们用于这个响应,那么您可以使用静态方法,就像在课程中一样


祝你好运

我建议使用hasMnayThrow:并在这种情况下加载它。但现在我意识到,
title
from
chapter\u sections
表也是必需的。我已经更新了问题