R
R
Ruslan Ruslanov2018-12-29 09:51:19
Yii
Ruslan Ruslanov, 2018-12-29 09:51:19

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,
            ]);
        }

this works, but with a large number of entries, the pages load in 10+ seconds, and this is unacceptable.
how to rewrite this piece of code? in fact, I just need to find out the id of neighboring elements, but so far I have not come up with anything else.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Antony Tkachenko, 2018-12-29
@LemonFox

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;

The decision is on the forehead, if you think about it, you can find better options (but it doesn’t matter).
P.S. before working with orm, I advise you to familiarize yourself with mysql at least in order to understand what query is needed and how to organize a competent database structure.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question