php - 如何过滤 Eloquent 结果并保留一些特定的列(有关系)

标签 php orm eloquent laravel-5

我有一个 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/

相关文章:

php - 如何修复 Laravel "Unknown column <column_name> in field list"

php - NetBeans 中的 Sublime Text 3 提示

python - Django 的单例架构是否使其无法作为库中的独立 ORM 工作?

php - 有条件地将属性 append 到 Laravel 中的模型

Django 自定义字段列未创建

php - Eloquent:find() 和 where() 用法 laravel

javascript - WordPress:PHP 变量在 JavaScript 中显示为空

PHP比较时间戳和实时时间的差异

javascript - 提交表单之前返回确认对话框不起作用

php - Laravel 5.2 Eloquent ORM hasManyThrough