简介
在许多博客和社区文章底部都有上一篇或者下一篇的链接,有童鞋问这个yii2要如何实现呢?其实很简单,稍微点一下大家就明白了。
实例
其实很简单,我们有的条件就是当前文章的ID($id),那么我们去查询当前id的下一条有效的数据就是下一篇的内容了,看下代码
1.yii2中默认的详情页是如下所示:
1
2
3
4
5
6
|
public
function
actionView(
$id
)
{
return
$this
->render(
'view'
, [
'model'
=>
$this
->findModel(
$id
),
]);
}
|
2.在这里添加一段查询下一条数据的代码既可(post为文章模型)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
function
actionView(
$id
)
{
//下一篇内容获取
$res
= Post::find()->where([
'>'
,
'id'
,
$id
])->one();
if
(
$res
){
$next
[
'url'
] = yii\helpers\Url::to([
'post/view'
,
'id'
=>
$res
->id]);
$next
[
'title'
] =
$res
->title;
}
else
{
$next
[
'url'
] =
'#'
;
$next
[
'title'
] =
'没有文章了'
;
}
return
$this
->render(
'view'
, [
'model'
=>
$this
->findModel(
$id
),
'next'
=>
$next
]);
}
|
3.剩下的就是在对应的位置,添加上下一篇的内容即可
1
2
3
|
<
div
>
下一篇:<
a
href="<?=$next['url']?>"><?=$next['title']?></
a
>
</
div
>
|
上一篇的做法与上述的方式相同,通过使用yii2的简单查询即可完成“上/下一篇”的小功能