首页 > 解决方案 > 在 Laravel 中,直接从视图向模型或控制器请求一些数据的最佳方式是什么?

问题描述

我有 2 张桌子:ProductsImages

每个产品有许多图像(通过 product_id 外键)

*product_id, product_title*
1, "Product 1"
2, "Product 2"
3, "Product 3"
4, "Product 4"
*image_id, product_id(foreign key), image_url, created_at*
25,  1,  "/filename_xyz", '5:00'
26,  1,  "/filename_abc", '5:30'
27,  2,  "/filename_def", '6:30'
28,  1,  "/filename_abc", '7:00'
29,  3,  "/filename_def", '8:00'

我有一个控制器,可以将所有产品返回到我的视图中。

产品控制器.php

public function index(){
        $data_to_return = Product::orderby('product_id', 'DESC')->paginate(10);

        return view('product.index', [
            'product_data' => $data_to_return,
        ]);
    }

此控制器正确加载到视图product.index中。

我成功地遍历了刀片文件中的结果,如下所示:

@foreach($product_data as $product)
{{ $product->product_title }}
<!--however, I would like to also print one of the images linked to a product-->
@endforeach

我在规划图像的“链接”或“加入”时遇到问题。对于 product_id=1 的产品,图像数据库中有多个条目。我希望我的视图能够从 Products 表中获取产品信息,以及从 Images 表中获取只有一个图像(匹配 product_id)。就我而言,我需要由 created_at ASC 订购的第一个结果(或限制 1)。

示例:产品 1 会将“/filename_xyz”的 image_url 带入我的视图,因为它是第一个从具有 product_id = 1 的图像创建的

我在想解决方案可能是这样的:

循环产品数组:

@foreach($product_data as $product)
{{ $product->product_title }}

<!-- And calling a controller like -->

{{Image::mainImage($product->id)}}

<!-- Where mainImage returns the image_url I am looking for-->
@endforeach

或者

更好地设计我的模型,首先以某种方式加入表格,这完成了我之前提到的只显示我感兴趣的一个图像。我不知道如何通过最好的 Laravel/Eloquent 实践来实现这一点。

标签: phplaraveleloquentlaravel-bladelaravel-7

解决方案


这就是 Eloquent 关系会派上用场的地方!

您的模型的关系应该类似于此设置;

class Product extends Model
{
    public function image()
    {
        return $this->hasOne('your/path/to/image/model');
    }
}

class ProductImage extends Model
{
    public function product()
    {
        return $this->belongsTo('your/path/to/product/model');
    }
}

如果设置正确,您会执行类似<img src="{{ $product->image->image_url }}">的操作以显示产品图像。这假设您每个产品只有一张图片。

在你的迁移中,比如在你的product_images表迁移中,你应该写$table->foreignId('product_id')->constrained();,Laravel 会自动知道在哪里寻找相应的图像条目。


推荐阅读