[英]How to fetch latest record of each user in a table using Laravel eloquent
我在一個表中有 n 個用戶,對於每個用戶,我將他們的登錄和注銷時間保存在一個單獨的表中。 我想使用 Laravel eloquent 獲取 2 天未登錄的用戶的詳細信息。
用戶表結構
id | name | email
日志表結構
id |action | user_id | created_at | updated_at
到目前為止,我已經做了很多:
$users = LogsData::where('action','Login')->where('created_at','<',Carbon::now()->subDays(1))->get();
但是 output 也有 2 天內登錄的用戶。
編輯:我收到了查詢,我需要將其轉換為 eloquent。
我自己解決了。 這是解決方案:
SELECT t1.* FROM actions t1
JOIN (SELECT user_id, MAX(id) as maxid FROM actions where action = "LOGIN" GROUP BY user_id) t2
ON t1.user_id = t2.user_id and t1.id = t2.maxid
where created_at < NOW() - INTERVAL 2 DAY
如果只需要獲取每個用戶最后的數據,可以將id
desc排序,然后按user_id
分組,獲取最新數據
$users = LogsData::where('action','Login')
->whereDate('created_at','<',Carbon::today()->subDays(1))
->orderBy('id', 'DESC')
->groupBy('user_id')
->get();
要使用groupBy
,您必須將配置值中的strict
更改為false
。 但是如果你不想改變你的配置文件,這個查詢可以幫助你。 只需翻譯成laravel查詢版
SELECT * FROM log_datas AS ld WHERE ld.action = 'Login' AND ld.id IN (SELECT MAX(id) FROM log_datas WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 DAY) GROUP_BY user_id)
您需要先連接到日志表,並且因為 MySQL 總是尋找阻力最小的路徑,所以您需要反過來加入它:可能不存在小於 1 天的日志條目。
$users = DB::from('users')
->leftJoin('logs', function ($join) {
$join->on('users.id', '=', 'logs.user_id')
->where('logs.action', '=', 'Login')
->where('logs.created_at', '>=', Carbon::now()->subDays(2));
})
->whereNull('logs.id')
->get();
也許嘗試使用 eloquent 關系
記下您的命名空間,確保 App\LogsData 例如在這里是正確的
// in your User Model
public function logsData()
{
return $this->hasMany('App\LogsData');
}
// in your LogsData Model
public function user()
{
return $this->belongsTo('App\User');
}
public function scopeLoginActions($query)
{
return $query->where('action', 'Login');
}
然后你可以訪問數據
User::whereHas('logsData', function ($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2));
})->get();
// and if you require the login records
User::with('logsData')->whereHas('logsData', function ($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2));
})->get();
// and if you require an individual login record
User::with(['logsData' => function($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2))->first();
})->whereHas('logsData', function ($query) {
$query->loginActions()->where('created_at', '<', now()->subDays(2));
})->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.