我在Yii2中的模型中添加了以下函数:
public function getNext() {
$next = $this->find()->where(['>', 'id', $this->id])->one();
return $next;
}
public function getPrev() {
$prev = $this->find()->where(['<', 'id', $this->id])->orderBy('id desc')->one();
return $prev;
}
Run Code Online (Sandbox Code Playgroud)
我做了一个函数来让你想要的那些id.我建议你在模型中声明它:
public static function getNextOrPrevId($currentId, $nextOrPrev)
{
$records=NULL;
if($nextOrPrev == "prev")
$order="id DESC";
if($nextOrPrev == "next")
$order="id ASC";
$records=YourModel::model()->findAll(
array('select'=>'id', 'order'=>$order)
);
foreach($records as $i=>$r)
if($r->id == $currentId)
return isset($records[$i+1]->id) ? $records[$i+1]->id : NULL;
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
因此,要使用它,您所要做的就是:
YourModel::getNextOrPrevId($id /*(current id)*/, "prev" /*(or "next")*/);
Run Code Online (Sandbox Code Playgroud)
它将返回下一个或上一个记录的相应ID.
我没有测试它,所以试一试,如果出现问题,请告诉我.