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

Laravel关联products与sync_statuses表,基于DateTime列比较查询

Laravel 关联查询:筛选未同步/更新后的未删除产品

看起来你需要在Laravel里构建一个关联查询,筛选出未软删除且更新时间晚于最后同步时间的产品数据。我来帮你完善这段代码,并提供几种不同场景下的写法:

基础内连接写法(仅取有同步记录且满足条件的产品)

如果你的需求是只获取那些存在对应sync_statuses记录,且更新时间晚于同步时间的未删除产品,可以用以下优化后的代码:

$products = DB::table('products')
    ->join('sync_statuses', function ($join) {
        // 关联两个表的product_number字段
        $join->on('products.product_number', '=', 'sync_statuses.product_number')
             // 关联时加入时间对比条件
             ->where('products.updated_at', '>', 'sync_statuses.synced_at');
    })
    // 全局筛选未软删除的产品(这里建议移到join外,确保所有未删除产品都被考虑)
    ->whereNull('products.deleted_at')
    // 按需选择需要的字段,比如products的所有字段+同步时间
    ->select('products.*', 'sync_statuses.synced_at')
    ->get();

左连接写法(包含从未同步过的未删除产品)

如果你的需求还需要包含从未有过同步记录的未删除产品(也就是sync_statuses中没有对应记录的产品),可以使用左连接:

$products = DB::table('products')
    ->leftJoin('sync_statuses', 'products.product_number', '=', 'sync_statuses.product_number')
    // 筛选条件:要么没有同步记录,要么更新时间晚于同步时间
    ->where(function ($query) {
        $query->whereNull('sync_statuses.product_number')
              ->orWhere('products.updated_at', '>', 'sync_statuses.synced_at');
    })
    ->whereNull('products.deleted_at')
    ->select('products.*', 'sync_statuses.synced_at')
    ->get();

Eloquent 模型写法(更优雅的ORM方式)

如果你的项目中已经定义了Eloquent模型(比如Product和SyncStatus),可以用关联查询的方式,代码可读性更高:

首先在Product模型中定义关联关系:

// app/Models/Product.php
public function syncStatus()
{
    return $this->hasOne(SyncStatus::class, 'product_number', 'product_number');
}

然后执行查询:

// 仅取有同步记录且满足条件的未删除产品
$products = Product::whereNull('deleted_at')
    ->whereHas('syncStatus', function ($query) {
        $query->where('products.updated_at', '>', 'sync_statuses.synced_at');
    })
    ->get();

// 包含从未同步过的未删除产品
$products = Product::whereNull('deleted_at')
    ->where(function ($query) {
        $query->doesntHave('syncStatus')
              ->orWhereHas('syncStatus', function ($subQuery) {
                  $subQuery->where('products.updated_at', '>', 'sync_statuses.synced_at');
              });
    })
    ->get();

注意事项

  • 确保products和sync_statuses表的product_number字段是索引字段,否则关联查询会很慢。
  • 如果sync_statuses中一个产品可能有多条记录,建议先获取每个产品的最新同步记录,再进行关联(比如用groupBy或子查询)。

内容的提问来源于stack exchange,提问作者Jideobi Benedine Ofomah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:44:50