English 中文(简体)
查阅关于Yei的数据库的下版和前版。
原标题:get next & previous id record in database on Yii
  • 时间:2012-01-15 18:16:10
  •  标签:
  • php
  • mysql
  • yii

我需要下班;在Yi框架数据库中,先前曾作过这样的记录,以便下游和背后导航纽吨?

最佳回答

我发挥了作用,让这些人不去找你。 我建议你在模式中宣布:

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;
}

因此,你必须做的是:

YourModel::getNextOrPrevId($id /*(current id)*/, "prev" /*(or "next")*/); 

它将退还下一个或以往记录的相应副本。

我没有试过,因此给它一个尝试,如果有些错的话,请让我知道。

问题回答

I added following functions in my model in 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;
}

• 私人var,用于其他功能。

在《示范法》中:

class Model1 .....
{
   ...
   private _prevId = null;
   private _nextId = null;
   ...

   public function afterFind()  //this function will be called after your every find call
   {
    //find/calculate/set $this->_prevId;
    //find/calculate/set $this->_nextId;
   }

   public function getPrevId() {
      return $this->prevId;
   }

   public function getNextId() {
      return $this->nextId;
   }

}

核对“观点”链接中产生的代码,并使用“观点”文档中“Prev/Net”链接的改动

$model(or $data)->prevId/nextId

in the array( id =>#) section.

Taking the original answer and adapting it for Yii2 with a little clean up:

/**
 * [nextOrPrev description]
 * @source http://stackoverflow.com/questions/8872101/get-next-previous-id-record-in-database-on-yii
 * @param  integer $currentId [description]
 * @param  string  $nextOrPrev  [description]
 * @return integer         [description]
 */
public static function nextOrPrev($currentId, $nextOrPrev =  next )
{
    $order   = ($nextOrPrev ==  next ) ?  id ASC  :  id DESC ;
    $records = 
amespacepathModel::find()->orderBy($order)->all();

    foreach ($records as $i => $r) {

       if ($r->id == $currentId) {
          return ($records[$i+1]->id ? $records[$i+1]->id : NULL);
       }

    }

    return false;
}

我的实施工作基于搜索模型。

主计长:

public function actionView($id)
{
    // ... some code before

    // Get prev and next orders
    // Setup search model
    $searchModel = new OrderSearch();
    $orderSearch = yiihelpersJson::decode(Yii::$app->getRequest()->getCookies()->getValue( s-  . Yii::$app->user->identity->id));
    $params = [];
    if (!empty($orderSearch)){
        $params[ OrderSearch ] = $orderSearch;
    }
    $dataProvider = $searchModel->search($params);
    $sort = $dataProvider->getSort();
    $sort->defaultOrder = [ created  => SORT_DESC];
    $dataProvider->setSort($sort);

    // Get page number by searching current ID key in models
    $pageNum = array_search($id, array_column($dataProvider->getModels(),  id ));
    $count = $dataProvider->getCount();
    $dataProvider->pagination->pageSize = 1;

    $orderPrev = $orderNext = null;
    if ($pageNum > 0) {
        $dataProvider->pagination->setPage($pageNum - 1);
        $dataProvider->refresh();
        $orderPrev = $dataProvider->getModels()[0];
    }
    if ($pageNum < $count) {
        $dataProvider->pagination->setPage($pageNum + 1);
        $dataProvider->refresh();
        $orderNext = $dataProvider->getModels()[0];
    }
    // ... some code after
}

OrderSearch:

public function search($params)
{
    // Set cookie with search params
    Yii::$app->response->cookies->add(new yiiwebCookie([
         name  =>  s-  . Yii::$app->user->identity->id,
         value  => yiihelpersJson::encode($params[ OrderSearch ]),
         expire  => 2147483647,
    ]));

    // ... search model code here ...
}

PS: be sure if you can use array_column for array of objects. This works good in PHP 7+ but in lower versions you got to extract id by yourself. Maybe it s good idea to use array_walk or array_filter in PHP 5.4+

充分利用亚洲开发银行的发动机/优化(当其作为主要关键时):

Model:

  public static function getNextPrevId($currentId)
    {
        $queryprev = new Query();
        $queryprev->select( max(id) )->from(self::tableName())->where( id<:id ,[ id =>$currentId]);
        $querynext = new Query();
        $querynext->select( min(id) )->from(self::tableName())->where( id>:id ,[ id =>$currentId]);

        return [ $queryprev->scalar(), $querynext->scalar()];
        
    }

主计长:

public function actionView($id) {
    return $this->render( view , [
         model  => $this->findModel($id),
         nextprev  => YourModel::getNextPrevId($id),
    ]);
}

观点:

<?= !is_null($nextprev[0]) ? Html::a( ⇦ , [ view ,  id  => $nextprev[0]], [ class  =>  btn btn-primary ]) :    ?>
<?= !is_null($nextprev[1]) ? Html::a( ⇨ , [ view ,  id  => $nextprev[1]], [ class  =>  btn btn-primary ]) :    ?>

以前的解决办法在你获得第一个或最后记录时有问题,而且正在向数据库发出多次电话。 在这里,我的工作解决办法是在一个方面运作的,它处理的是最终的、可分割的各州:

在模型内:

public static function NextOrPrev($currentId)
{
    $records = <Table>::find()->orderBy( id DESC )->all();

    foreach ($records as $i => $record) {
        if ($record->id == $currentId) {
            $next = isset($records[$i - 1]->id)?$records[$i - 1]->id:null;
            $prev = isset($records[$i + 1]->id)?$records[$i + 1]->id:null;
            break;
        }
    }
    return [ next =>$next,  prev =>$prev];
}

Within the controller:

     public function actionView($id)
{
    $index = <modelName>::nextOrPrev($id);
    $nextID = $index[ next ];
    $disableNext = ($nextID===null)? disabled :null;
    $prevID = $index[ prev ];
    $disablePrev = ($prevID===null)? disabled :null;

    // usual detail-view model
    $model = $this->findModel($id);

    return $this->render( view , [
         model  => $model, 
         nextID =>$nextID,
         prevID =>$prevID,
         disableNext =>$disableNext,
         disablePrev =>$disablePrev,
    ]);
}

认为:

<?= Html::a( Next , [ view ,  id  => $nextID], [ class  =>  btn btn-primary r-align btn-sm  .$disableNext]) ?>
<?= Html::a( Prev , [ view ,  id  => $prevID], [ class  =>  btn btn-primary r-align btn-sm  .$disablePrev]) ?>




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签