Laravel错误:使用Resource :: collection时在字符串上调用成员函数first()

时间:2019-05-26 13:34:01

标签: php laravel api laravel-5 laravel-5.8

我正在创建一个具有多个商店的后端。每个商店都有自己的产品

我已经创建了一个商店和一个产品,并正在尝试将产品分配给所有商店。

当我尝试将产品添加到StoreResource.php的商店中

使用:

'products' => ProductResource::collection($this->products),

我得到了错误:

  

在字符串上调用成员函数first()

我一直在寻找许多解释和教程,但遇到相同的错误

*存储模型*

public function products()
{
  return $this->hasMany(Product::class);
}

*商店控制器*

public function index()
{
    return StoreResource::collection(Store::with('products')->paginate(5));
}

存储资源

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class StoreResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
         'id' => $this->id,
         'name' => $this->name,
         'description' => $this->description,
         'image' => $this->image,
         'created_at' => (string) $this->created_at,
         'updated_at' => (string) $this->updated_at,
         'products' => ProductResource::collection($this->products),
       ];
    }
}

*产品型号*

public function stores()
{
    return $this->belongsTo(Store::class);
}

*产品负责人*

public function index()
{
    return ProductResource::collection(Product::with('stores')->paginate(5));
}

产品资源

<?php

namespace App\Http\Resources;


use Illuminate\Http\Resources\Json\JsonResource;

class Purchaseresource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
      return [
        'id' => $this->id,
        'productName' => $this->productName,
        'amount' => $this->amount,
        'total_product_price' => $this->total_product_price,
        'week' => $this->week,
        'day' => $this->day,
        'month' => $this->month,
        'year' => $this->year,
        'created_at' => (string) $this->created_at,
        'updated_at' => (string) $this->updated_at,
      ];
   }
}

我希望在商店和产品之间建立联系,以便它们在API响应中显示为这样

 {
    "id": 0, 
    "name": "Store", 
    "image": "image",
    "products": [
        {
            "id": 1,
            "name": "product",
            "price": 7,
            "qty": 100,
            "total": 0
        },
     ]    
}

因此产品将被嵌套在商店中。

1 个答案:

答案 0 :(得分:0)

您首先需要在控制器中进行查询,例如:

$query = Store::all();

,然后出现类似的内容:

$stores = StoreResource::collection($query);

,您可以在“资源”中通过:

'product' => $this->product

在资源数组中