Laravel eloquent查询某id后的最新20条记录?

Laravel eloquent query 20 latest records in after an id?

我有一个记录的id。我需要查询在id为

的记录之前更新的20条最新记录

像这样

$orders = Order::latest('updated_at')->take(20)->before(id)->get();

我正在使用laravel5.5

编辑

看了答案感觉自己的问题不够清楚

假设这是我的数据库 table 我的 ID 是 5

---------------------------------
|id| name | updated_at          |
|--|------|---------------------|
|1 |a     | 2017-09-21 06:27:59 |
|2 |b     | 2017-09-19 06:20:29 |
|3 |c     | 2017-09-12 05:27:59 |
|4 |d     | 2017-09-18 05:17:39 |
|5 |e     | 2017-09-17 06:27:48 |
|6 |b     | 2017-09-19 06:27:59 |
|7 |f     | 2017-09-04 06:27:58 |
|8 |g     | 2017-09-06 06:27:14 |

我想要最近更新的记录所以

---------------------------------
|id| name | updated_at          |
|--|------|---------------------|
|1 |a     | 2017-09-21 06:27:59 |
|2 |b     | 2017-09-19 06:20:29 |
|4 |d     | 2017-09-18 05:17:39 |
|5 |e     | 2017-09-17 06:27:48 |
|3 |c     | 2017-09-12 05:27:59 |
|6 |b     | 2017-09-09 06:27:59 |
|8 |g     | 2017-09-06 06:27:14 |
|7 |f     | 2017-09-04 06:27:58 |

现在有 20(在本例中为所有)记录在 ID 为 5 的记录之前更新

---------------------------------
|id| name | updated_at          |
|--|------|---------------------|
|3 |c     | 2017-09-12 05:27:59 |
|6 |b     | 2017-09-09 06:27:59 |
|8 |g     | 2017-09-06 06:27:14 |
|7 |f     | 2017-09-04 06:27:58 |

这就是我需要的结果。

你可以像这样使用查询

select * from yourtable as t
inner join (
    SELECT * FROM `yourtable` WHERE id = 590  
) as tm
on t.updated_at < tm.updated_at order by t.updated_at desc
limit 10

与 eloquent orm:

用您的 ID 替换 590

$orders = Order::join(
        \DB::raw(
            '(select updated_at AS ddd from orders where id = 590) AS t'),
        't.ddd',
        '>',
        'orders.updated_at'
    )->latest('updated_at')->take(20)->get();

这样的事情怎么样:

$id;
$num = 20;

$orders = Order::where('id', '<=', $id - $num)
               ->orderBy('updated_at', 'desc')
               ->take($num)
               ->get();

或者

$id;
$range = 20;
$query = [];

foreach (range($id - $range, $id) as $idNumber) {
    $query[] = $idNumber;
}

$orders = Order::find($query)->orderBy('updated_at', 'desc');

https://laravel.com/docs/5.5/eloquent

如果碰巧你在 Laravel 中进行复杂查询,你会想使用数据库 class https://laravel.com/docs/5.5/database#database-transactions

试试这样的东西,看看它是否能满足您的需求

$orders = Order::orderBy('updated_at', 'desc')->get();

$index = $orders->search(function (Order $order) {
    return $order->id === 5;
});

$orders = $orders->splice($index+1, 20);