【发布时间】:2015-02-02 02:25:36
【问题描述】:
来自Laravel 4 and Eloquent ORM - How to select the last 5 rows of a table,但我的问题有点不同。
我如何返回按创建方式 (ASC) 排序的最后 N 条记录。
因此例如按顺序插入以下记录:
first
second
third
fourth
fifth
我希望查询返回最后 2 条记录
fourth
fifth
【问题讨论】:
来自Laravel 4 and Eloquent ORM - How to select the last 5 rows of a table,但我的问题有点不同。
我如何返回按创建方式 (ASC) 排序的最后 N 条记录。
因此例如按顺序插入以下记录:
first
second
third
fourth
fifth
我希望查询返回最后 2 条记录
fourth
fifth
【问题讨论】:
Laravel 偏移量
DB::table('users')->skip(<NUMBER Calulation>)->take(5)->get();
您可以通过获取当前查询的计数并跳过 $query->count() - 5 来计算 N,以获取最后 5 条记录或任何您想要的。
前
$query = User::all();
$count = ($query->count()) - 5;
$query = $query->skip($count)->get();
【讨论】:
skip 时再次获取。
在纯 SQL 中,这是通过使用子查询来完成的。像这样的:
SELECT * FROM (
SELECT * FROM foo
ORDER BY created_at DES
LIMIT 2
) as sub
ORDER BY created_at ASC
所以限制发生在子查询中,然后在主查询中顺序被颠倒。 Laravel 并没有真正支持子查询。但是你仍然可以这样做:
$sub = DB::table('foo')->latest()->take(2);
$result = DB::table(DB::raw('(' . $sub->toSql() . ') as sub'))
->oldest()
->get();
如果你使用 Eloquent:
$sub = Foo::latest()->take(2);
$result = Foo::from(DB::raw('(' . $sub->toSql() . ') as sub'))
->oldest()
->get();
注意latest和oldest只需分别添加orderBy('created_at)和desc和asc。
【讨论】: