我正在尝试返回带有资源的模型数据,但它说:
调用模型 [应用\产品] 上的未定义关系 [品牌]。
法典
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;
}
}
有什么想法吗?
更新
如果我从零件中删除它说:brandwith()
Call to undefined method App\Product::belongTo()
30秒到达战场