Php 如何使用Laravel eloquent获取表中每个用户的最新记录
我在一个表中有n个用户,对于每个用户,我在一个单独的表中保存他们的登录和注销时间。我想使用Laravel eloquent获得2天未登录用户的详细信息 用户表结构Php 如何使用Laravel eloquent获取表中每个用户的最新记录,php,sql,laravel,eloquent,laravel-7,Php,Sql,Laravel,Eloquent,Laravel 7,我在一个表中有n个用户,对于每个用户,我在一个单独的表中保存他们的登录和注销时间。我想使用Laravel eloquent获得2天未登录用户的详细信息 用户表结构 id | name | email id |action | user_id | created_at | updated_at 日志表结构 id | name | email id |action | user_id | created_at | updated_at 到目前为止,我已经做了很多: $users = Logs
id | name | email
id |action | user_id | created_at | updated_at
日志表结构
id | name | email
id |action | user_id | created_at | updated_at
到目前为止,我已经做了很多:
$users = LogsData::where('action','Login')->where('created_at','<',Carbon::now()->subDays(1))->get();
$users=LogsData::where('action','Login')->where('created_at','如果您只需要获取每个用户的最后一个数据,您可以对id
desc排序,然后按user_id
分组以获取最新数据
$users = LogsData::where('action','Login')
->whereDate('created_at','<',Carbon::today()->subDays(1))
->orderBy('id', 'DESC')
->groupBy('user_id')
->get();
您需要首先连接到logs表,因为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();
也许可以尝试使用雄辩的关系
注意您的名称空间,确保App\LogsData在此处是正确的
//在您的用户模型中
公共功能日志数据()
{
返回$this->hasMany('App\LogsData');
}
//在你的LogsData模型中
公共函数用户()
{
返回$this->belongsTo('App\User');
}
公共函数scopeLoginActions($query)
{
返回$query->where('action','Login');
}
然后,您可以使用
用户::whereHas('logsData',函数($query){
$query->loginActions()->其中('created_at','justgroup by
user_id@Saengdaet我可以在非键列中使用group by吗?任何其他解决方案?是否在用户模型中设置了关系?不,不是。我没有设置任何关系。它正在引发异常。包含功能上不依赖group by子句中的列的非聚合列…转到 config/database.php
然后更改strict=>false
我已经更新了我的答案,也许你可以在数据库中尝试原始查询以确保result@Saengdaet这真的对我有用-谢谢