我有一个 Eloquent 问题:
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"
}
]
使用 Array 和 Collection 方法实现此目的的最佳方法是什么?如果有一种方法可以只用 Eloquent 来实现这一点,那就更好了。
最佳答案
我在最近的一个项目中做了类似的事情,改编如下:
$person = Person::with('mother','father')->find(1);
$arrPerson = $person->toArray();
$arrPerson['mother'] = $person->mother->name;
$arrPerson['father'] = $person->father->name;
如果您只需要指示的那些,您可以扩展它以清除其他元素。
关于php - 如何过滤 Eloquent 结果并保留一些特定的列(有关系),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29689753/