【问题标题】:Laravel - Relationship With Resources and whenLoaded Not WorkingLaravel - 与资源的关系和加载时不起作用
【发布时间】: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();

【问题讨论】:

    标签: php laravel laravel-relations laravel-resource


    【解决方案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之前的符号是什么??

      【讨论】:

        猜你喜欢
        • 2019-11-05
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        相关资源
        最近更新 更多