Answer the question
In order to leave comments, you need to log in
How to optimize this piece of code?
yii2 rendering post view, also need to add forward and back buttons to navigate through posts.
done, looks like this:
public function actionView($id)
{
// $model = Images::findOne(['id' => $id]);
$next = $id;
$prev = $id;
$all = Images::find()->all();
foreach ($all as $key => $item) {
if ($item['id'] == $id){
$model = $item;
if (array_key_exists($key + 1, $all)){
$next = $all[$key + 1]['id'];
}
if (array_key_exists($key - 1, $all)){
$prev = $all[$key - 1]['id'];
}
break;
}
}
if (!$model || !$id){
throw new HttpException(404, '404');
}
return $this->render('view', [
'model' => $model,
'next' => $next,
'prev' => $prev,
]);
}
Answer the question
In order to leave comments, you need to log in
Make just normal queries, there is no need to sort through the entire table.
//next
SELECT * FROM foo WHERE id > <your_id> ORDER BY id LIMIT 1;
//prev
SELECT * FROM foo WHERE id < <your_id> ORDER BY id LIMIT 1;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question