简体   繁体   English

通过雄辩的拉拉维夫(Lelavel laravel)与组获取最小(日期),最大(日期)

[英]Get min(date), max(date) with group by eloquent laravel

This query is for getting other data with the highest value of date with the group by/unique. 该查询用于通过group by / unique获取具有日期最高值的其他数据。 Here I used unique in place of group by. 在这里,我用唯一代替了分组依据。
My question is how to get min(date) and max(date) with group by/unique. 我的问题是如何通过group by / unique获取min(date)和max(date)。 The group by/unique is for Dataset table's date field. 分组依据/唯一性用于数据集表的日期字段。
I have searched for this but not getting exact solution that how to get max and min date with group by/unique in laravel eloquent. 我已经搜索了这个,但是没有获得确切的解决方案,即如何在laravel中雄辩地通过group // unique获得最大和最小日期。
In table structure, there are multiple entries for one code so here I used group by/unique to get one record for the code. 在表结构中,一个代码有多个条目,因此在这里我使用group by / unique来获取该代码的一条记录。

There can be multiple dates as 02-01-2003,01-03-2007,01-01-2019, 01-07-2018... etc. with same/ different code. 可以有多个日期,例如02-01-2003、01-03-2007、01-01-2019、01-07-2018 ...等。使用相同/不同的代码。 If I group by with code then get onmy one record per code. 如果我按代码分组,则每个代码只记录一条记录。 So here I want to select the max date [01-01-2019] and min date [02-01-2003]. 所以在这里我想选择最大日期[01-01-2019]和最小日期[02-01-2003]。

Thanks in advance. 提前致谢。

Controller: 控制器:

$datasets = Dataset::where('user_id', $user_id)
          ->orderBy('date','desc')
          ->get(['code', 'access','user_id','date'])
          ->unique('code');

Try to select max and min date like this: 尝试选择最大和最小日期,如下所示:

$datasets = Dataset::select('code', 'access','user_id', DB::raw('MAX(date) as max_date'),  DB::raw('MIN(date) as min_date'))
                    ->where('user_id', $user_id)
                    ->orderBy('date','desc')
                    ->get()
                    ->unique('code');

Finally I got solution but this can not be the exact solution but as I am beginner and not getting the exact solution I do this functionality as below: 最终我得到了解决方案,但这不能是确切的解决方案,但是由于我是初学者,但没有得到确切的解决方案,因此我执行以下功能:

I created two different queries to get min and max values. 我创建了两个不同的查询来获取最小值和最大值。

$min_datasets = Dataset::where('user_id', $user_id)
      ->orderBy('date','asc')
      ->get(['code', 'access','user_id','date'])
      ->unique('code');


$max_$datasets = Dataset::where('user_id', $user_id)
      ->orderBy('date','desc')
      ->get(['code', 'access','user_id','date'])
      ->unique('code');
$data = DB::table('table_name')->where('user_id',$user_id)
->select('code','access','user_id','date')
->whereBetween('date', [02-01-2003, 01-01-2019])
->groupBy('unique_column')
->get()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM