Laravel 中嵌套 api 资源时如何避免无限循环?

Vic*_*tor 2 laravel laravel-5

我有两个模型:CompanyRepresentative。代表属于公司,公司有多名代表。

我还有两个相应的资源。

公司资源

public function toArray($request)
    {
        return [
            'id'          => $this->id,
            'title'       => $this->title,   
            'representatives' => RepresentativeResource::collection($this->representatives)
        ];
    } 
Run Code Online (Sandbox Code Playgroud)

代表资源

 public function toArray($request)
    {
        return [
            'id' => $this->id,
            'company' => $this->company ? new CompanyResource($this->company) : null
        ];
    }
Run Code Online (Sandbox Code Playgroud)

我想要实现的目标是,当我找到公司时,我想找到他们的代表。当我获得代表时,我想获得有关公司的信息。

发生的是无限循环:它们无限地相互包含。

那么,如何解决呢?

P. *_*lul 8

你尝试使用过吗whenLoaded?它记录在此处,我认为它适合您的需求。

对于你的代码,你应该有这样的东西:

class CompanyResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,   
            'representatives' => RepresentativeResource::collection(
                $this->whenLoaded('representatives')
            )
        ];
    } 
}
Run Code Online (Sandbox Code Playgroud)
class RepresentativeResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'company' => new CompanyResource(
                $this->whenLoaded('company')
            )
        ];
    } 
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的控制器中,您必须加载与模型的关系。

new RepresentativeResource(Representative::with('company')->first());
Run Code Online (Sandbox Code Playgroud)