API资源:尽管对象属性出现在对象

时间:2017-10-16 15:21:10

标签: php laravel laravel-5

我使用Laravel 5.5 API资源转换一些数据。资源的toArray方法如下所示:

public function toArray($request)
{
    return [
        'building' => [
                parent::toArray($request)
        ],
        'construction' => [
            $this->construction
        ],
        'renovations' => $this->renovations,
        'names' => $this->names
    ];
}

以下是我如何在控制器中调用资源:

$data = new BuildingResource(Building::find($buildingId))

当我返回$data时,我得到以下输出:

{
    "building": [
        {
            "id": 167,
            "building_id": "470",
            "name": "Pharmacy",
            "from_year": 1929,
            "to_year": 1988
        }
    ],
    "construction": [
        {
            "id": 167,
            "building_id": "470",
            "architect": "Walter Scholer",
            "cost": 175000,
            "materials": "Brick"
        }
    ],
    "renovations": [
        {
            "id": 31,
            "building_id": "470",
            "from_year": 1947,
            "to_year": "",
            "architect": "",
            "contractor": "",
        },
        {
            "id": 32,
            "building_id": "470",
            "from_year": 1989,
            "to_year": "",
            "architect": "Walter Scholer and Associates, Inc.",
        }
    ],
    "names": [
        {
            "id": 183,
            "building_id": "470",
            "displayname": 0,
            "abbreviation": "",
            "name": "Geosciences",
            "from_year": 1970,
            "to_year": 1988
        },
        {
            "id": 184,
            "building_id": "470",
            "displayname": 1,
            "abbreviation": "SCHL",
            "name": "Hall of Student Services",
            "from_year": 1988,
            "to_year": ""
        }
    ]
}

我遇到的问题是我可以访问此对象的所有属性,除了建筑物'。 $data->construction$data->renovations$data->names都按预期工作并返回相应的数据。但是,$data->building返回null。

然而,当我返回$data->id时,我从建筑物数组中的对象获取ID。

出于绝望,我已经尝试$data->building['0']$data['building']$data['building']['0'] - 这些都没有效果。

我还尝试明确设置构建对象的键和值(而不是使用parent::toArray($request)并获得相同的结果。

我的目标只是使用$data->building->id获取值,就像我可以获取返回对象的其他属性一样。

感谢。

0 个答案:

没有答案