ThinkPHP中取得上下篇文章的方法
在开发文章类网站时,经常需要获取当前文章的上一篇和下一篇。下面分享一个ThinkPHP中的实现方法。
代码实现
//取得上下篇文章
function PrevNext($id, $name = '', $where = array(), $fields = 'id,title'){
$array = array();
$model = M($name);
$map = array();
// 获取上一篇(ID小于当前文章)
$map = $where;
$map['id'] = array('lt',$id);
$prevL = $model->field($fields)->where($map)->order('id desc')->find();
if(!$prevL){
$prevL['id'] = '';
$prevL['title'] = '暂无';
}
// 获取下一篇(ID大于当前文章)
$map['id'] = array('gt',$id);
$nextL = $model->field($fields)->where($map)->order('id asc')->find();
if(!$nextL){
$nextL['id'] = '';
$nextL['title'] = '暂无';
}
$array['prev'] = $prevL;
$array['next'] = $nextL;
return $array;
}
方法说明
- $id - 当前文章的ID
- $name - 模型名称,为空则使用当前模型
- $where - 额外的查询条件
- $fields - 要查询的字段,默认 id,title
返回值
函数返回一个包含 prev 和 next 两个元素的数组:
- prev - 上一篇文章(id更小的文章,按ID倒序取第一条)
- next - 下一篇文章(id更大的文章,按ID正序取第一条)
调用示例
$id = 10; // 当前文章ID
$result = PrevNext($id, 'article');
// 显示上一篇
if($result['prev']['id']){
echo '上一篇:'.$result['prev']['title'].'';
} else {
echo '上一篇:暂无';
}
// 显示下一篇
if($result['next']['id']){
echo '下一篇:'.$result['next']['title'].'';
} else {
echo '下一篇:暂无';
}
扩展思路
这个方法可以稍作修改应用到其他场景:
- 按其他字段排序(如发布日期、点击量等)
- 添加分类限制,只获取同分类的文章
- 添加状态限制,只获取已发布的文章
- 兼容其他框架,如Laravel、Yii等
其他框架适配示例
Laravel版本:
function PrevNext($id, $model = 'Article', $where = [], $fields = ['id', 'title'])
{
$prev = $model::where(array_merge($where, [['id', '<', $id]]))->orderBy('id', 'desc')->first($fields);
$next = $model::where(array_merge($where, [['id', '>', $id]]))->orderBy('id', 'asc')->first($fields);
return [
'prev' => $prev ?: ['id' => '', 'title' => '暂无'],
'next' => $next ?: ['id' => '', 'title' => '暂无'],
];
}
方法的核心思路是一致的:通过当前ID查找相邻记录,只是具体语法不同而已。

发表评论 取消回复