Principles of previous and next pages
Sort by id to get the information of the previous article sorted by the current id, and the information of the next article by the current id.
1. Simple and direct way
$last = Article::where('id', '<', $info->id)->orderBy('id', 'desc')->first();
$next = Article::where('id', '>', $info->id)->orderBy('id', 'asc')->first();
Can generate data from two articles.
Second, the upgrade method
$last = Article::where('id', '<', $info->id)->latest('id')->first();
$next = Article::where('id', '>', $info->id)->oldest('id')->first();
Use the built-in laravel latest
and oldest
instead orderBy
, look elegant and a little, but do things the same way with the above. Request the database twice to obtain two articles.
3. Upgrade again
$sql = Article::where('id', '<', $info->id)->latest('id')->take(1);
$list = Article::where('id', '>', $info->id)->oldest('id')->take(1)->union($sql)->orderBy('id', 'asc')->get();
You can also get the two articles from the previous article and the next article. Without losing the elegant posture, the union
method combines two queries into one, reducing the pressure of the database request. The method
used at the same time orderBy
sorted the two data found. The information in the previous article is the one with subscript 0. The next article information is the one with the subscript 1.
Use the following ->dd()
method to print out mysql
the statement details.
$list = Article::where('id', '>', $info->id)->oldest('id')->take(1)->union($sql)->orderBy('id', 'asc')->dd();
The results are as follows:
(select * from `articles` where `id` > ? order by `id` asc limit 1) union (select * from `articles` where `id` < ? order by `id` desc limit 1) order by `id` asc
array:2 [▼
0 => 3
1 => 3
]
It can be seen that it is a statement query combined by two queries.