在Yii上获取数据库中的下一个和上一个id记录

Abu*_*yah 0 php mysql yii

我需要在Yii框架的数据库中使用next和之前的id记录来制作导航按钮吗?

Ulu*_*gov 9

我在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)

  • 到目前为止最好的答案.大多数人使用 - > all(),这是浪费资源IMO. (2认同)

Alf*_*cia 5

我做了一个函数来让你想要的那些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.

我没有测试它,所以试一试,如果出现问题,请告诉我.