假设我有两个表:
表1:家庭(家庭ID,姓氏)
表2:人员(人员ID,名字,家庭ID)
我正在尝试使用Medoo数据库框架来获取这种json结果:
[
{
family_id: '1',
last_name: 'Doe',
persons: [
{person_id: '1', first_name: 'John'},
{person_id: '3', first_name: 'Jane'}
]
},
{
family_id: '2',
last_name: 'Wayne',
persons: [
{person_id: '2', first_name: 'Thomas'},
{person_id: '4', first_name: 'Martha'},
{person_id: '5', first_name: 'Bruce'}
]
}
]
我尝试过:
$families = $db->select(
'family',
[
'[>]person' => ['family_id' => 'family_id'],
],
[
'family.family_id',
'family.last_name',
'person.person_id',
'person.first_name',
]
);
返回:
[
{
family_id: '1',
last_name: 'Doe',
person_id: '1',
first_name: 'John'
},
{
family_id: '1',
last_name: 'Doe',
person_id: '3',
first_name: 'Jane'
},
{
family_id: '2',
last_name: 'Wayne',
person_id: '2',
first_name: 'Thomas'
},
{
family_id: '2',
last_name: 'Wayne',
person_id: '4',
first_name: 'MArtha'
},
{
family_id: '2',
last_name: 'Wayne',
person_id: '5',
first_name: 'Bruce'
}
]
我也尝试过:
$families = $db->select('family', ['family_id', 'last_name']);
foreach ($families as $key => $family) {
$families[$key]['persons'] = $db->select(
'person',
[
'person_id',
'first_name',
],
[
'person.family_id' => $family['family_id']
]
);
}
我获得了理想的结果,但对性能产生了巨大的影响。
有人知道Medoo解决方案来快速正确地做到这一点吗?
免责声明:此表与实际情况不符。我模拟了此表,以便于解释。实际情况要复杂得多,而且命名可能会使其他人感到困惑。因此,由于实际方案具有数千行,因此上述解决方案对性能的影响显而易见。