我有两个在线商店的mySQL表:
产品(cols:id等)
图片(cols:id, product_id ,文件路径等)
products表中的任何 product 产品可能具有无限数量的图片!
因此,我的产品模型如下:
class Product extends Model
{
public function pictures()
{
return $this->hasMany('App\Picture');
}
}
我的图片模型如下:
class Picture extends Model
{
//
}
现在,我正在尝试列出所有产品一起及其相应的图片数据集。我尝试运行多个代码。但是,以下代码均无效:
\App\Product::pictures()->get()
不起作用!显示此错误:
Non-static method App\Product::pictures() should not be called statically
我还尝试了其他方法,例如
\App\Product::with('pictures')->get());
错误:
Trying to get property 'filepath' of non-object (View: /home/vagrant/testproject/resources/views/products.blade.php)
备注:Filepath是一列图片。我正在尝试像这样在刀片中访问它:
{{$products->picture->filepath}}
我现在在这个小事情上工作了几个小时-但是我不明白我做错了什么吗?任何帮助深表感谢!谢谢你们!
答案 0 :(得分:1)
您正在做的事情有两个潜在问题。
{{$products->picture->filepath}}
,所以我认为您的行为像这样: $products = \App\Product::with('pictures')->get());
这里$products
是Product
模型的集合。该集合没有picture
属性。
@foreach($products as $product)
{{$product->picture->filepath}}
@endforeach
除非每种产品都有图片,否则可能会导致您所说的错误。如果产品没有图片,那么您将在null上调用filepath。您可以通过几种方式解决此问题,我将在下面列出其中一种:
@foreach($products as $product)
@if(!empty($product->picture))
{{$product->picture->filepath}}
@endif
@endforeach
正如OP在下面的评论中指出的,根本问题是这种关系有很多。因此,要使用图片,您应该这样做:
@foreach($products as $product)
@foreach($product->pictures as $picture)
{{$picture->filepath}}
@endforeach
@endforeach