L
L
Light7772016-01-19 18:51:35
Yii
Light777, 2016-01-19 18:51:35

How to randomly display records from a table in Yii2?

There is a site similar to a simple blog.
Entries from the database are displayed on the main feed of posts.
The problem is creating the "Also interesting on the topic" block (there are in all blogs on the side, links to other posts)
I don’t know how to randomly display records from the database
In the controller, I transfer all records from the database to the view

public function actionBlog()
    {
        $posts = Posts::find();
        $countQuery = clone $posts;
        $pages = new Pagination(['totalCount' => $countQuery->count(),
            'pageSize' => '2',]);
        $models = $posts->offset($pages->offset)
        ->limit($pages->limit)
        ->all();
        return $this->render('blog',[
           'models' => $models,
           'pages' => $pages,]);
    }

In the view, I catch all the records and output them to the tape like this
<?php foreach( $models as $post): ?>
                    <li>
                        <div class="post-content">
                            <a href="<?= Url::toRoute(['blogpost', 'id' => $post['post_id']]);?>" title=<?=$post['post_title']?> class="post-image">
                                <img src=<?='/acs/backend/web/'.$post['post_photo'];?> alt="" style="display: block;">
                            </a>

                            <h2 class="box-header align-left"><a href="<?= Url::toRoute(['blogpost', 'id' => $post['post_id']]);?>"><?=$post['post_title']?></a></h2>
                            <p class="description t1"><?=$post['post_brief']?></p>
                            <div class="row padding-top-54 padding-bottom-17">
                                <a class="more" href="<?= Url::toRoute(['blogpost', 'id' => $post['post_id']]);?>" title="Подробнее">Подробнее</a>
                            </div>
                        </div>
                    </li>
                <?php endforeach ;?>
                <?php echo LinkPager::widget(['pagination' => $pages,]);?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Bay, 2016-01-19
@kawabanga

->orderBy('RAND()') try when fetching models.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question