gpt4 book ai didi

mysql - 如何选择按日期列 desc 排序的不同记录 - Laravel

转载 作者:行者123 更新时间:2023-11-29 09:32:36 25 4
gpt4 key购买 nike

我有这样的表:

app_id | releaseDate 
111 | 2019-04-21
111 | 2019-05-10
222 | 2019-07-21
222 | 2019-04-22
222 | 2019-05-25
333 | 2019-06-21
333 | 2019-05-21

我需要得到这样的结果(需要按releaseDate排序desc并在选择不同的之后):

111 | 2019-05-10
222 | 2019-07-21
333 | 2019-06-21

我的代码:

$apps_histories = ApplicationHistory::with('application')->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
->orderBy('releaseDate', 'DESC')
->groupBy('app_id')
->get();

我得到了:

111 | 2019-04-21
222 | 2019-04-22
333 | 2019-05-21

我尝试了不同的方法,但我不明白为什么它没有按我的预期工作。你能帮忙吗?

最佳答案

您可以通过两种方式实现此行为。第一个是使用原始查询来过滤查询中的 releaseDate:

$apps_histories = ApplicationHistory::with('application')
->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
->select(\DB::raw('*, max(releaseDate) as releaseDate'))
->orderBy('releaseDate', 'DESC')
->groupBy('app_id')
->get();

另一种方法是在结果Collection中使用unique函数。请注意,此选项未针对大型结果表进行优化:

$apps_histories = ApplicationHistory::with('application')
->whereBetween('releaseDate', ['2014-10-01', '2019-10-14'])
->orderBy('releaseDate', 'DESC')
->get()
->unique('app_id');

关于mysql - 如何选择按日期列 desc 排序的不同记录 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58382357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com