gpt4 book ai didi

mysql - 如何使用 Eloquent 按日期列排序?

转载 作者:行者123 更新时间:2023-11-28 23:18:20 24 4
gpt4 key购买 nike

所以我有模型 Foo 和 Bar。 Foo 有很多 Bars,Bar 属于 Foo。

我正在尝试获取按其最新/最新 Bar 排序的 Foos 集合。

$foos = Foo::select('foo.*', 'bar.id as bar_id', 'bar.created_at AS bar_created_at')
->join('bar', function($join) {
$join->on('foo.id', '=', 'bar.foo_id')
->where('bar.baz', '=', 1)
->where('bar.foobaz', '=', 1);
})
->groupBy('bar_id')
->orderBy('bar_created_at', 'desc')
->get();

但是当我 dd($foos->lists('bar_created_at', 'id')); 我看到日期不是最新的 Bar 记录,它们实际上是最旧的.

这是生成的 SQL:

select `foo`.*, `bar`.`foo_id` as `foo_id`, `bar`.`created_at` as `bar_created_at` from `foo` inner join `bar` on `foo`.`id` = `bar`.`foo_id` and `bar`.`foo` = ? and `bar`.`foobaz` = ? where `foo`.`deleted_at` is null group by `foo_id` order by `bar_created_at` desc

如有任何帮助,我们将不胜感激。我正在使用 Laravel 5.0。

最佳答案

您需要按 foo.id 分组并按 MAX(bar.created_at) 排序:

$foos = Foo::select('foo.*', DB::raw('MAX(bar.created_at) AS bar_created_at)')
->join('bar', function($join) {
$join->on('foo.id', '=', 'bar.foo_id')
->where('bar.baz', '=', 1)
->where('bar.foobaz', '=', 1);
})
->groupBy('foo.id')
->orderBy('bar_created_at', 'desc')
->get();

而且您不需要将 wehere 条件放入连接中:

$foos = Foo::select('foo.*', DB::raw('MAX(bar.created_at) AS bar_created_at)')
->join('bar', 'foo.id', '=', 'bar.foo_id')
->where('bar.baz', '=', 1)
->where('bar.foobaz', '=', 1);
->groupBy('foo.id')
->orderBy('bar_created_at', 'desc')
->get();

这应该生成以下查询:

select `foo`.*,  MAX(bar.created_at) as bar_created_at
from `foo`
inner join `bar` on `foo`.`id` = `bar`.`foo_id`
where `foo`.`deleted_at` is null
and `bar`.`foo` = ?
and `bar`.`foobaz` = ?
group by `foo.id`
order by `bar_created_at` desc

关于mysql - 如何使用 Eloquent 按日期列排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863569/

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