Laravel - 与资源的关系和加载时不起作用

Posted

技术标签:

【中文标题】Laravel - 与资源的关系和加载时不起作用【英文标题】:Laravel - Relationship With Resources and whenLoaded Not Working 【发布时间】:2021-12-16 15:03:51 【问题描述】:

所以我正在尝试利用资源来控制输出,因为有人告诉我这是为 api 输出建模数据的最佳方式。

客户模型

 public function invoices () 
        return $this->hasMany('\App\Models\Invoice');
    

发票型号:

public function customer() 
        return $this->belongsTo('\App\Models\Customer');
    

客户资源:

public function toArray($request)
    
        return [
            'id' => $this->id,
            'invoices' => InvoiceResource::collection('invoices')
        ];
    

发票资源:

public function toArray($request)

    $customer = $this->whenLoaded('customer');
    return [
      'id' => $this->id,
      'customer' => CustomerResource::collection($this->whenLoaded($customer)),
    ];

客户控制器:

public function index()
    
        $customers = Customer::with(['invoices']);
        return CustomerResource::collection($customers->paginate(50))->response();
    

但是当我去 API EndPoint 时

Error
Call to a member function first() on string

Illuminate\Http\Resources\Json\ResourceCollection::collectResource
vendor/laravel/framework/src/Illuminate/Http/Resources/CollectsResources.php:30

错误从堆栈开始: return CustomerResource::collection($customers->paginate(50))->response();

【问题讨论】:

【参考方案1】:

我有两个问题 第 1 期 发票资源:

public function toArray($request)

    $customer = $this->whenLoaded('customer');
    return [
      'id' => $this->id,
      'customer' => CustomerResource::collection($this->whenLoaded($customer)),
    ];

需要


    $customer = $this->whenLoaded('customer');
    return [
      'id' => $this->id,
      'customer' => CustomerResource::collection($this->whenLoaded($customer)),
    ];

第二客户资源:

public function toArray($request)
    
        return [
            'id' => $this->id,
            'invoices' => InvoiceResource::collection('invoices')
        ];
    

需要

public function toArray($request)
    
        return [
            'id' => $this->id,
            'invoices' => InvoiceResource::collection($this->whenLoaded('invoices'))
        ];
    

【讨论】:

【参考方案2】:

每张发票只有一个客户,对吧?所以:

'customer' => new CustomerResource($this->whenLoaded('customer')),

还有$customer之前的符号是什么??

【讨论】:

以上是关于Laravel - 与资源的关系和加载时不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 7雄辩的关系不起作用

Laravel 5.8多态关系`nullableMorphs`不起作用

带有前缀和资源的laravel嵌套路由不起作用

Laravel - 自引用关系不起作用

Laravel 8 多对多关系不起作用(没有抛出错误)

Laravel 5.6 OneToOne 关系不起作用