我有这种雄辩:
$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
。
由于
答案 0 :(得分:0)
您可以在不必使用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;
答案 1 :(得分:0)
现在我尝试的是我按递减顺序对表进行排序,以便在按用户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;
答案 2 :(得分:0)
无需进行原始查询。
$users = [1,2,3,4,5];
$transactions = Transaction::whereIn('user_id', $users)
->whereDate('created_at', '=', Carbon::today()->subDays(30)->toDateString())->get();
return $transactions;
答案 3 :(得分:0)
你必须使用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;