【问题标题】:Laravel Eloquent methods inside ViewView 中的 Laravel Eloquent 方法
【发布时间】:2014-08-13 08:25:58
【问题描述】:

我有两个模型,分别称为 ProductProductImage。我还有一个视图,我想列出所有产品及其相关ProductImage,其中属性main_image 等于1。在ProductController 中,我调用模型Product 的方法all() 并将其存储在视图的data 数组中,这样我就可以遍历视图内的产品。但在那个循环中,我想展示该产品的相关主图像。我可以通过在视图中调用 where()first 等 Eloquent 方法来做到这一点吗?

您好,

一月

【问题讨论】:

    标签: php view model laravel-4 eloquent


    【解决方案1】:

    这就是你需要的:http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/

    只有你的关系看起来像这样:

    public function mainImage()
    {
      return $this->hasOne('ProductImage')->where('main_image', 1);
    }
    

    那么你可以简单地做这样的事情:

    // fetch
    $products = Product::with('mainImage')->paginate(10);
    
    // output
    @foreach($products as $product)
      ...
      <img src="{{ $product->mainImage->url }}" />
      ...
    @endforeach
    

    【讨论】:

    • 非常感谢!这就是我一直在寻找的。​​span>
    【解决方案2】:

    我猜你的 ProductImage 实体对你的 Product 实体有一个外键。所以,Product 可以有多个 ProductImage。

    在您的产品模型中,您可以添加以下内容:

    public function images()
    {
        return $this->hasMany('ProductImage');
    }
    

    在你看来:

    @foreach($product->images as $image)
        // Do what you want.
    @endforeach
    

    希望我能理解你的问题。

    【讨论】:

    • 但是如果我想在图像上使用 where 语句,我也可以在视图中执行此操作吗?喜欢$product-&gt;images()-&gt;where() as $image
    • 我认为视图不是你应该使用 where 语句的地方。如果你必须做一个特定的处理,你应该在模型中为它​​创建一个函数,并在控制器中调用它,将结果传递给只会显示它的视图。这是我对如何使用 MVC 的看法,但也许有更正确的方法来做到这一点。
    • 所以在我的模型中我必须创建一个类似scopeAllProductsWithImages 的方法并在该方法中进行内部连接?
    • 您可以使用手动连接来实现您所需要的,但您也可以充分利用框架并使用帮助关系来让您急切加载所需的图像。详情请查看我的回答。
    猜你喜欢
    • 2018-01-09
    • 1970-01-01
    • 2017-02-19
    • 2019-07-09
    • 2021-10-21
    • 1970-01-01
    • 2016-10-12
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多