Php 如何筛选有说服力的结果并保留某些特定列(具有关系)
我有一个雄辩的疑问:Php 如何筛选有说服力的结果并保留某些特定列(具有关系),php,orm,eloquent,laravel-5,Php,Orm,Eloquent,Laravel 5,我有一个雄辩的疑问: Person::with('mother','father')->find(1); 将输出此结果: [ { id: "1", name: "John", mother_id: "4", father_id: "5" mother: { id: "4", name: "Sarah" mother_id: "10
Person::with('mother','father')->find(1);
将输出此结果:
[
{
id: "1",
name: "John",
mother_id: "4",
father_id: "5"
mother: {
id: "4",
name: "Sarah"
mother_id: "10",
father_id: "20"
},
father: {
id: "5",
name: "Tony",
mother_id: "21",
father_id: "32"
}
}
]
但我想得到这样的东西:
[
{
name: "John",
mother: "Sarah",
father: "Tony"
}
]
使用数组和收集方法实现这一点的最佳方法是什么?如果有一种方法可以通过雄辩来实现这一点,那就更好了。我在最近的一个项目中做了类似的事情,改编如下:
$person = Person::with('mother','father')->find(1);
$arrPerson = $person->toArray();
$arrPerson['mother'] = $person->mother->name;
$arrPerson['father'] = $person->father->name;
如果您只需要指定的元素,那么可以扩展它以清除其他元素。您可以在Person模型上创建一个getNames(或类似的)访问器,该访问器只返回名称。像您这样使用渴望加载,我相信无论哪种方式都会执行三个查询。也许这是可能的,但是,我如何才能“平显”结果,使其成为一维数组?