我在产品和照片之间写了一个关系belongsToMany,现在我想在主页上显示产品。我是这样做的:
@foreach ($latestProducts as $product)
<img src="{{$product->photos()->path}}">
@endforeachhomeController:
public function index()
{
$latestProducts = Product::orderBy('created_at' , 'desc')->limit(10)->get();
return view('front.layouts.index' , compact('latestProducts'));
}照片模型:
public function products() {
return $this->belongsToMany(Product::class);
}产品型号:
public function photos() {
return $this->belongsToMany(Photo::class);
}我得到了未定义的属性:当我编写{{$ Illuminate\Database\Eloquent\Relations\BelongsToMany::$path -> .And -> path }时,错误更改为“未定义的数组键0”。此外,当我编写{$Product->.And->path}}时,我会得到一个错误,因为“此集合实例上不存在属性路径”。
发布于 2022-09-22 10:21:40
我相信您在photo模型中有一个Photo属性/字段。因为photos是一组照片,所以您可能需要编写:
@foreach ($latestProducts as $product)
@foreach ($product->photos as $photo)
<img src="{{$photo->path}}">
@endforeach
@endforeach只有第一张照片:
@foreach ($latestProducts as $product)
<img src="{{$product->photos->first()->path}}">
@endforeach
// Or to be safe
@foreach ($latestProducts as $product)
<img src="{{optional($product->photos->first())->path}}">
@endforeach
// Or this in php 8
@foreach ($latestProducts as $product)
<img src="{{$product->photos->first()?->path}}">
@endforeach发布于 2022-09-22 09:09:57
你必须用
{{ $product->photos->path }}因为当你处理刀片中的关系时,你把它作为父亲类的一个属性来处理,不像你用雄辩的ORM来处理它,你可以使用photos()
发布于 2022-09-22 09:34:19
基本上,错误是说$products中没有属性照片。假设表名正确,外键也正确
你可以这样做:
public function index()
{
$latestProducts = Product::with('photos')->orderBy('created_at' , 'desc')->limit(10)->get();
return view('front.layouts.index' , compact('latestProducts'));
}在刀片文件中,尝试删除(),因为它将加载关系。
@foreach ($latestProducts->photos as $product)
<img src="{{$product->path}}">
@endforeachhttps://stackoverflow.com/questions/73811942
复制相似问题