Laravel雄辩地指出,最长日期等于过去30天


Laravel eloquent where max date equal to past 30 days

我有一个雄辩的:

$users = [1,2,3,4,5];
$transactions = Transaction::whereIn('user_id', $users)
            ->where(DB::raw('DATE(MAX(created_at))'), Carbon::now()->subMonth()->format('Y-m-d'))->get();
return $transactions;

但它返回给我这个错误:General error: 1111 Invalid use of group function (SQL: select * from transactions where 0 = 1

我如何获得所有用户的最后一笔交易等于过去30天?

以下是原始查询以备不时之需:

select * from `transactions` where `0` = 1 and DATE(MAX(created_at)) = ?

表格结构:

Users Table: id (not autoincrement), name, gender, created_at

Transactions Table: id (not autoincrement), user_id (FK), amount, created_at

我目前的解决方案:

迭代每个用户并检查他们的最大created_at

感谢

您可以简单地执行此操作,而不必使用DB::raw()查询。

试试这个:

$users = [1,2,3,4,5];
$transactions = Transaction::whereIn('user_id', $users)
            ->where('created_at', '=', Carbon::now()->format('Y-m-d'))
            ->get();
return $transactions;

不需要进行原始查询。

$users = [1,2,3,4,5];
$transactions = Transaction::whereIn('user_id', $users)
                ->whereDate('created_at', '=', Carbon::today()->subDays(30)->toDateString())->get();
return $transactions;

您必须使用whereBetween

$users = [1,2,3,4,5];
$transactions = Transaction::select(DB::raw('DATE(MAX(created_at))'))->whereIn('user_id', $users)
        ->whereBetween('created_at',array(Carbon::now(),Carbon::now()->subMonth()->format('Y-m-d')))->get();
return $transactions;

现在我尝试的是按递减顺序对表进行排序,以评估最新记录何时按用户Id分组…

$users = [1,2,3,4,5];
$transactions = Transaction::select(DB::raw('select id from transactions order by transaction.created_at desc as table1' )->leftJoin('transactions','id','=','table1.id')->whereIn('user_id', $users)
            ->where('created_at', '=', Carbon::now()->subMonth()->format('Y-m-d'))->groupBy('transaction.user_id')
            ->get();
return $transactions;