【问题标题】:Laravel error: Call to a member function first() on string when using Resource::collectionLaravel 错误:使用 Resource::collection 时在字符串上调用成员函数 first()
【发布时间】:2019-10-12 07:34:25
【问题描述】:

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

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

当我尝试将我的产品添加到我在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
        },
     ]    
}

所以产品会嵌套在商店中。

【问题讨论】:

  • 在哪一行和文件中抛出错误?
  • 我刚刚想通了,需要从商店模型、控制器等中删除产品,然后使用'product' =&gt; $this-&gt;product,

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


【解决方案1】:

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

$query = Store::all();

之后是这样的:

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

在你的资源中你可以通过:

'product' => $this->product

在资源数组中

【讨论】:

    猜你喜欢
    • 2017-03-24
    • 2020-10-22
    • 2020-03-01
    • 1970-01-01
    • 2019-11-04
    • 2017-12-04
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多