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

问题描述 投票:0回答:1

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

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

[当我尝试将产品添加到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));
}

STORE资源] >>

<?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
        },
     ]    
}

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

我正在创建一个具有多个商店的后端。每个商店都有自己的产品,我已经创建了一个商店和一个产品,并且正在尝试将产品分配给所有商店。当我尝试添加我的...

php laravel api laravel-5 laravel-5.8
1个回答
0
投票

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

$query = Store::all();
© www.soinside.com 2019 - 2024. All rights reserved.