我有一个have资源,但是它说没有定义常量id
class DashboardGraphDataResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => id,
'technology' => technology,
'area' => area,
'totalCapacity' => total_capacity,
'working' => working,
'fileDate' => file_date,
'created_at' => created_at,
'updated_at' => updated_at,
];
}}
代码在我的控制器内
return DashboardGraphDataResource::collection(DashboardGraphData::all());但是当我返回DashboardGraphData::all()时,没有将它放在DashboardGraphDataResource::collection()中,结果将显示出来。
[{"id":1,"technology":"tech1","area":1,"total_capacity":"2936","working":936,"file_date":"2020-01-05","created_at":"2020-05-05 03:47:27","updated_at":"2020-05-05 03:47:27"}]我的查询有什么问题吗?请帮助我:(
发布于 2020-05-05 04:19:04
使用$this->id而不是id
return [
'id' => $this->id,
'technology' => $this->technology,
'area' => $this->area,
'totalCapacity' => $this->total_capacity,
'working' => $this->working,
'fileDate' => $this->file_date,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];发布于 2020-05-05 04:25:35
使用$request->id insted id
return [
'id' => $request->id,
'technology' => $request->technology,
'area' => $request->area,
'totalCapacity' => $request->total_capacity,
'working' => $request->working,
'fileDate' => $request->file_date,
'created_at' => $request->created_at,
'updated_at' => $request->updated_at,
];发布于 2020-05-05 05:01:36
这更像是PHP错误,而不是Laravel错误。我来解释几件事。
常量与局部变量:
函数接受一个名为$request的参数。请求参数包含传递给它的所有信息。我假设您传递一个数组或对象,其中包含键/属性id、technology、area、total_capacity、working、file_date、created_at和updated_at。
代码的问题是,您正在试图填充的每个数组值中调用一个常量。PHP中的常量是具有固定值的名称或标识符。它们类似于变量,除非一旦定义了它们,它们就不能被修改/更改。
常量在PHP中以字母或下划线开头,在常量名称之前没有$符号。
在您的示例中,我认为您正在尝试从$request对象/数组访问属性/键值。
您可以通过执行$request->property_name_here或$request['key_name_here']访问它们,并使用值填充数组。希望这能有所帮助。
https://stackoverflow.com/questions/61605677
复制相似问题