Я создаю бэкэнд с несколькими магазинами.Каждый магазин со своими продуктами
Я создал магазин и продукт и пытаюсь доставить продукты во все магазины.
Когда я пытаюсь добавить мои товары в мой магазин в StoreResource.php
, используя:
'products' => ProductResource::collection($this->products),
Я получаю ошибку:
Сначала вызовите функцию-член () в строке
Я искал в Интернете многочисленные объяснения и руководства, но столкнулся с той же ошибкой
* STORE MODEL*
public function products()
{
return $this->hasMany(Product::class);
}
* STORE CONTROLLER *
public function index()
{
return StoreResource::collection(Store::with('products')->paginate(5));
}
STORE Resource
<?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
},
]
}
Так чтотовар станет вложенным в магазин.