php - Laravel 连接 2 个表,第一个表中的一个数据和第二个表中的多行

标签 php mysql json laravel-5 laravel-query-builder

FirstTable

id | name |


1 | student1 |

2 | student2 |

3 | student3 |

4 | student4 |

================================

SecondTable

Id | stud_id | subject | mark


1 | 1 | maths | 50

2 | 1 | english | 45

3 | 2 | maths | 20

4 | 3 | maths | 40

我如何使用上面的表结构在 laravel 中查询.. 我需要输出为

{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}

最佳答案

我已经在 Laravel 查询生成器中完成了它。 请参阅下文。

$stud = DB::table('FirstTable')
               ->join('SecondTable','FirstTable.id','=','SecondTable.stud_id')
               ->where('FirstTable.id','=','1')
               ->get();
dd($stud);

关于php - Laravel 连接 2 个表,第一个表中的一个数据和第二个表中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47628847/

相关文章:

php - 为什么在fetchAll()之前需要execute()

php - FosUserBundle 与 FosRestBundle 集成

php - 在进入数据库之前如何检查值是否为空?

从 vb 应用程序插入的 mysql (phpmyadmin) 行没有得到更新

javascript - 扩展JS 4.1.3 : How to get a value from a JSON store

php - 带有单数/复数词的 NumberFormatter

php - 批量导入自定义属性 Magento

php - 从多个表的一个主键中获取数据库中的数据

arrays - Mongodb集合转换

javascript从对象数组中提取相同的键值