laravel - 如何从嵌套关系中获取特定列 - 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",
}
]
是否有任何关系方式,或者我必须使用连接来获得上述输出
解决方案
您也可以通过在章节章节上使用 with 来将章节放在章节章节中,就像您在课程中所做的那样。
如果您想让它们与所有响应一起出现,那么您可以在章节章节中声明 $with。
如果您只想让它们用于此响应,那么您可以使用静态方法,就像您在课程中所做的那样。
祝你好运
推荐阅读
- java - Nosuchmethoderror:org.glassfish.jersey.internal.l10n.LocalizableMessageFactory
- flutter - 颤振抽屉测试错误,“A RenderFlex 在右侧溢出 188 像素”。
- python - 如何将类似字符串的字节转换为普通字节?
- java - 如何获得波斯地址
- java - 我的可执行 JavaFX 文件如何连接到 MySQL 数据库?
- c# - 清除 mdf 数据库时自动递增的主键
- go - 具有文件名“插入”的无效标识符字符
- django - 在 django 中添加个人资料图像不起作用
- microsoft-graph-api - 哪个文档描述了 microsoft graph php sdk 中每个 api 调用的结果类?
- javascript - 添加带有 html 背景的透明图标