繁体   English   中英

Laravel Eloquent ORM 一对多关系,ZE0626222614BEE31951D84C64EE5 来自两个表

[英]Laravel Eloquent ORM One-to-Many Relationship, Select from two Tables

我有两个网上商店的 mySQL 表:

产品(cols:id等...)

图片(列:id、 product_id 、文件路径等...)

products-table 的任何产品都可能有无限数量的图片

因此,我的产品模型如下所示:

class Product extends Model
{
    public function pictures()
    {
        return $this->hasMany('App\Picture');
    }
}

我的图片 model 看起来像这样:

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)

备注:文件路径是一列图片。 我正在尝试像这样在刀片中访问它:

{{$products->picture->filepath}}

我现在在这个小东西上工作了几个小时——但我就是不明白我做错了什么? 非常感谢任何帮助! 感谢你们!

你正在做的事情有两个潜在的问题。

  1. 您正在使用{{$products->picture->filepath}}所以我假设您正在执行以下操作:

$products = \App\Product::with('pictures')->get());

这里$productsProduct模型的集合。 该集合没有picture属性。

  1. 您正在遍历产品,例如
@foreach($products as $product)
    {{$product->picture->filepath}}
@endforeach

除非每个产品都有图片,否则这可能会导致您所说的错误。 如果产品没有图片,那么您将调用 null 上的文件路径。 您可以通过多种方式解决此问题,我将在下面列出一种:

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM