Laravel 9中关联Product与ProductImage表获取产品最后一条图片记录
Laravel 9 实现关联查询获取每个产品的最后一张图片
方式一:Eloquent 关联(推荐)
先定义模型及关联关系:
Product 模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\HasMany; class Product extends Model { // 指定表名(匹配用户给定的表名) protected $table = 'Product'; // 关联该产品的所有图片 public function productImages(): HasMany { return $this->hasMany(ProductImage::class, 'product_id', 'id'); } // 关联该产品的最新一张图片(Laravel 9+ 专属方法) public function latestProductImage(): HasOne { return $this->hasOne(ProductImage::class, 'product_id', 'id')->latestOfMany(); } }
ProductImage 模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; class ProductImage extends Model { protected $table = 'ProductImage'; }
执行查询
通过预加载关联获取数据,再整理为目标格式:
$products = Product::with('latestProductImage') ->select('id', 'product_name') ->get() ->transform(function ($product) { return [ 'id' => $product->id, 'product_name' => $product->product_name, 'product_id' => $product->latestProductImage?->product_id, 'product_image' => $product->latestProductImage?->product_image ]; });
方式二:查询构建器
通过子查询分组获取每个产品的最新图片ID,再关联查询:
use Illuminate\Support\Facades\DB; $products = DB::table('Product') ->select( 'Product.id', 'Product.product_name', 'ProductImage.product_id', 'ProductImage.product_image' ) // 子查询:获取每个 product_id 对应的最大图片ID(默认最新插入的ID最大) ->joinSub( DB::table('ProductImage') ->select('product_id', DB::raw('MAX(id) as latest_image_id')) ->groupBy('product_id'), 'latest_images', fn($join) => $join->on('Product.id', '=', 'latest_images.product_id') ) // 关联图片表获取对应记录 ->join('ProductImage', 'latest_images.latest_image_id', '=', 'ProductImage.id') ->get();
补充说明
- 若“最后一条图片”的判定不是按ID排序,可调整
latestOfMany()或子查询的排序字段(比如按created_at时间排序); - Eloquent方式更贴合Laravel ORM设计,代码可读性更高;查询构建器方式则更适合复杂场景的自定义SQL需求。
内容的提问来源于stack exchange,提问作者Aikee Masa
相关产品推荐
相关产品推荐

