如何在Laravel查询构造器中获取创建早于出价的关联商品
解决方案
直接在whereHas的闭包中添加whereColumn条件来对比两个表的创建时间,同时优化子查询提升性能,修改后的代码如下:
$query = ProductBid::whereStatus(ProductBid::STATUS_ACTIVE) ->whereNot('user_id', Auth::id()); $query->whereHas('product', function ($q) { // 优化子查询:直接传递查询构造器,无需提前get() $q->whereIn('code', Product::whereUserId(Auth::id())->select('code')) ->whereStatus(Product::STATUS_ACTIVE) // 添加创建时间对比条件 ->whereColumn('products.created_at', '<', 'product_bids.created_at'); });
关键说明:
- 使用
whereColumn而非普通where:因为要对比的是两张表的字段值,而非字段与固定值的比较,whereColumn支持跨表字段的直接对比。 - 子查询优化:原代码中
select('code')->get()会先执行一次查询并返回集合,改成直接传递Product::whereUserId(Auth::id())->select('code')后,Laravel会将其转换为数据库子查询,减少一次数据库请求,性能更优。
内容的提问来源于stack exchange,提问作者Have Fun Videos
相关产品推荐
相关产品推荐

