问题描述
我有2个表:产品和图片。
每个产品都有许多图像(通过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,"/filename_abc",'5:30'
27,2,"/filename_def",'6:30'
28,'7:00'
29,3,'8:00'
我有一个控制器,可以将所有产品返回我的视图。
ProductController.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的产品,“图像”数据库中有多个条目。我希望我的视图能够带来“产品”表中的产品信息以及“图像”表中的仅一张图像(匹配product_id)。就我而言,当由created_at ASC排序时,我需要第一个结果(或限制1)。
示例:产品1将带“ / filename_xyz”的image_url进入我的视图,因为它是首先从product_id = 1的Images中创建的那个
我在想解决方案可能是这样的:
环绕产品数组:
@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 /口才实践来实现这一目标。
解决方法
这就是雄辩的关系会派上用场的地方!
您的模型之间的关系应类似于此设置;
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会自动知道在哪里寻找对应的图像条目。