0

所以我试图利用资源来控制输出,因为有人告诉我这是为 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();

4

2 回答 2

0

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

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

还有什么是$sign before customer??

于 2021-11-02T10:26:49.973 回答
0

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

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'))
        ];
    }
于 2021-11-02T01:40:13.387 回答