我有一张唱片的id。我需要查询记录前更新的20条最新记录,并带有id。
像这样的东西
$orders = Order::latest('updated_at')->take(20)->before(id)->get();
我正在使用laravel5.5
修改
看看答案,我觉得我的问题不够明确。
假设这是我的数据库表,我的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 |
这是我需要的结果。
答案 0 :(得分:1)
你可以使用像这样的查询
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
凭借雄辩的orm:
用你的身份替换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();
答案 1 :(得分:0)
这样的事情怎么样:
$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中进行复杂的查询,你会想要使用DB类https://laravel.com/docs/5.5/database#database-transactions
答案 2 :(得分:0)
尝试这样的事情,看看它是否符合
之后的要求$orders = Order::orderBy('updated_at', 'desc')->get();
$index = $orders->search(function (Order $order) {
return $order->id === 5;
});
$orders = $orders->splice($index+1, 20);