我如何return按条目顺序最后n条记录

How do I return last n records in the order of entry

来自Laravel 4 and Eloquent ORM - How to select the last 5 rows of a table,但我的问题有点不同。

如何return最后 N 条记录按创建方式 (ASC) 排序。

因此,例如按顺序插入以下记录:

first
second
third
fourth
fifth

我想查询 return 最后 2 条记录

fourth
fifth

Laravel 偏移量

DB::table('users')->skip(<NUMBER Calulation>)->take(5)->get();

您可以通过获取当前查询的计数并跳过 $query->count() - 5 来获取最后 5 条记录或您想要的任何内容来计算 N。

$query = User::all();
$count = ($query->count()) - 5;

$query = $query->skip($count)->get();

在纯 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();

注意 latestoldest 分别添加一个 orderBy('created_at)descasc