Paginate加载了与Laravel API资源的关系

时间:2018-06-06 22:40:47

标签: laravel laravel-5.6

您好我正在laravel 5.6中的API资源上加载关系:

public function show($id)
{
    return new YardResource(Yard::find($id)->with('inspections')->paginate(1));
}

YardResource

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'maf_id' => $this->maf_id,
            'street' => $this->street,
            'suburb' => $this->suburb,
            'city' => $this->city,
            'country' => $this->country,
            'lat' => $this->lat,
            'long' => $this->long,
            'landowner_name' => $this->landowner_name,
            'landowner_phone' => $this->landowner_phone,
            'landowner_phone2' => $this->landowner_phone2,
            'landowner_mobile' => $this->landowner_mobile,
            'landowner_mobile2' => $this->landowner_mobile2,
            'landowner_email' => $this->landowner_email,
            'landowner_street' => $this->landowner_street,
            'landowner_suburb' => $this->landowner_suburb,
            'landowner_city' => $this->landowner_city,
            'landowner_country' => $this->landowner_country,
            'landowner_postcode' => $this->landowner_postcode,
            'acquired_at' => $this->acquired_at,
            'quarantined' => $this->quarantined,
            'archived' => $this->archived,
            'latest_inspection' => new Inspection($this->latestInspection),
            'inspections' => InspectionResource::collection($this->whenLoaded('inspections')),
            'tasks' => TaskResource::collection($this->tasks->where('completed', false)), // Get active tasks
            'feedings' => FeedResource::collection($this->feeds),
            'diseases' => DiseaseResource::collection($this->diseases),
            'treatments' => TreatmentResource::collection($this->activeTreatments), // between dates
            'yard_events' => YardEventResource::collection($this->yardEvents),
        ];
    }

我想要对'检查'关系进行分页,但我没有运气。

出现此错误:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id

任何帮助都会很棒!

3 个答案:

答案 0 :(得分:0)

paginate适用于集合,似乎你的toArray方法无法更改分页结果,因此将正常集合更改为所需的数组,然后将数组更改为集合并最终对其进行分页。 我想你可以这样做

$resultArray = new YardResource(Yard::find($id)->with('inspections')); // if your toArray method supports any size of objects 
$resultCollecttion = collect($resultArray);
return $resultCollection->paginate(1);

答案 1 :(得分:0)

这个问题很可能不是资源层本身,而是模型中实体的关系级故障。验证检查器模型是否与Yard正确相关。

如果确定没问题,那么在不添加关系的情况下测试资源的响应

return new YardResource(Yard::find($id)->paginate(1));

然后你可以准确地丢弃问题的来源

答案 2 :(得分:0)

变化:

Yard::with('inspections')->find($id);

为:

E2