在Yii上获取数据库中的下一个和上一个id记录
我做了一个函数来获得你要找的那些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;
}
因此,要使用它,你需要做的做的是这样的:
YourModel::getNextOrPrevId($id /*(current id)*/, "prev" /*(or "next")*/);
它会返回一个或下一个记录的对应的ID。
我没有测试它,所以试试看,如果出现问题,请让我知道。
创建一个私有变量,用于将信息传递给其他函数。
在型号:
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;
}
}
检查在ViewDetal链接生成和代码修改在_view文件中的上一个/净链路阵列( 'ID' 中使用
$model(or $data)->prevId/nextId
= >#)部分。
我说按照我的模型功能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;
}
迄今为止最好的答案。大多数人使用 - > all(),这是浪费资源IMO。 – vanarie 2018-02-04 07:50:20
以原来的答案,用少许清理适应它Yii2:
/**
* [nextOrPrev description]
* @source http://*.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 = \namespace\path\Model::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 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];
}
内的控制器:
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]) ?>
我的实现是基于SearchModel。
控制器:
public function actionView($id)
{
// ... some code before
// Get prev and next orders
// Setup search model
$searchModel = new OrderSearch();
$orderSearch = \yii\helpers\Json::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 \yii\web\Cookie([
'name' => 's-' . Yii::$app->user->identity->id,
'value' => \yii\helpers\Json::encode($params['OrderSearch']),
'expire' => 2147483647,
]));
// ... search model code here ...
}
PS:可以肯定的,如果你可以使用array_column
为对象的数组。 这适用于PHP 7+,但在较低版本中,您必须自行提取id
。在PHP 5中使用array_walk
或array_filter
也许是个好主意。4+
" class="dBlock left">Next – Abudayah 2012-01-16 08:04:01
我写PhotoController该功能 – Abudayah 2012-01-16 08:06:07
致命错误:既然你在控制器中声明该函数调用未定义的方法照片:: getPrevOrNextId() – Abudayah 2012-01-16 08:12:12