【问题标题】:Laravel join two tables with where that compares two date time columnsLaravel 连接两个表,其中比较两个日期时间列
【发布时间】:2018-04-11 14:43:08
【问题描述】:

我有两个表,我想使用两个日期时间列的值运行联合查询,我有 products 表和 sync_status 表,我想返回 updated_at 日期时间大于 synced_at 日期时间的所有产品。

DB::table('products')
    ->join('sync_statuses', function ($join) {
        $join->on('products.product_number', '=', 'sync_statuses.product_number')
            ->where('products.updated_at', '>', 'sync_statuses.synced_at')
            ->whereNull('products.deleted_at');
    })
    ->select('products.product_number');

这个 SQL 代表了我试图使用 Eloquent 实现的目标:

SELECT products.product_number
FROM products
JOIN push_statuses
ON products.product_number = statuses.product_number
AND (
  statuses.synced_at IS NULL
  OR products.updated_at > statuses.synced_at
)

【问题讨论】:

    标签: laravel eloquent laravel-eloquent


    【解决方案1】:

    您必须使用on() 而不是where() 来比较列:

    ->on('products.updated_at', '>', 'sync_statuses.synced_at')
    

    【讨论】:

      【解决方案2】:

      这对我有用:

      DB::table('products')
              ->join('statuses', function ($join) {
                  $join->on('products.product_number', '=', 'statuses.product_number')
                      ->where(DB::raw('products.updated_at'), '>=', DB::raw('statuses.synced_at'))
                      ->whereNull('products.deleted_at');
      
              })->select('products.product_number');
      

      我需要使用DB::raw('products.updated_at') 来引用 where() 子句中的每个日期时间列。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-17
        • 1970-01-01
        • 2020-07-26
        相关资源
        最近更新 更多