You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:15:35