我有两个模型:Company和Representative。代表属于公司,公司有多名代表。
我还有两个相应的资源。
公司资源:
public function toArray($request)
    {
        return [
            'id'          => $this->id,
            'title'       => $this->title,   
            'representatives' => RepresentativeResource::collection($this->representatives)
        ];
    } 
代表资源:
 public function toArray($request)
    {
        return [
            'id' => $this->id,
            'company' => $this->company ? new CompanyResource($this->company) : null
        ];
    }
我想要实现的目标是,当我找到公司时,我想找到他们的代表。当我获得代表时,我想获得有关公司的信息。
发生的是无限循环:它们无限地相互包含。
那么,如何解决呢?
你尝试使用过吗whenLoaded?它记录在此处,我认为它适合您的需求。
对于你的代码,你应该有这样的东西:
class CompanyResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,   
            'representatives' => RepresentativeResource::collection(
                $this->whenLoaded('representatives')
            )
        ];
    } 
}
class RepresentativeResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'company' => new CompanyResource(
                $this->whenLoaded('company')
            )
        ];
    } 
}
然后,在您的控制器中,您必须加载与模型的关系。
new RepresentativeResource(Representative::with('company')->first());
| 归档时间: | 
 | 
| 查看次数: | 2614 次 | 
| 最近记录: |