Laravel вызов неопределенного отношения [бренд] на модели [приложение \ продукт] - PullRequest
0 голосов
/ 27 января 2020

Я пытаюсь вернуть данные моей модели с ресурсом, но он говорит:

Вызов неопределенного отношения [бренда] для модели [Приложение \ Продукт].

Код

product.php

public function brand()
{
  return $this->belongTo(Brand::class);
}

brand.php

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

controller

public function show($slug)
{
  $product = Product::where('slug', $slug)->with(['photos', 'variations', 'options', 'brand'])->where('active', 'yes')->first();
  return response()->json([
    'data' => new ProductFrontResource($product),
    'message' => 'Product retrieved successfully.',
  ]);
}

ProductFrontResource.php

use App\Http\Resources\CategoryResource;

class ProductFrontResource extends JsonResource
{
    public function toArray($request)
    {
        $arrayData = [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'brand' => $this->brand->name,
            'categories' => CategoryResource::collection($this->whenLoaded('categories')),
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
        ];

        return $arrayData;
    }
}

Есть идеи?

Обновление

Если я удаляю brand из with() части, она говорит:

Call to undefined method App\Product::belongTo()

1 Ответ

3 голосов
/ 27 января 2020

изменить отношение бренда к этому.

public function brand()
{
  return $this->belongsTo(Brand::class);
}

источник laravel красноречивый

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...