Z
Z
ZaurK2019-05-03 11:29:42
Yii
ZaurK, 2019-05-03 11:29:42

How to combine pagination with a selection from the database?

Hello! There are two tables, album and photo, which are joined by a foreign key and have a one-to-many relationship. The challenge is to display albums with pagination, and the last photo from this album should be displayed on the album cover. At this stage, there was a problem with the correct wording of the request and pagination.

public function actionGalleryall()
       {

         $this->layout = 'inner';
         $query = Album::find()->joinWith('photo')->orderBy('id')->all();
         // echo '<pre>';
         // print_r($query);
         // die();
         $countQuery = clone $query;
         $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize'=>3]);
         $models = $query->offset($pages->offset)
          ->limit($pages->limit)
          ->all();

      return $this->render('albumsall', [
           'models' => $models,
           'pages' => $pages,
      ]);

       }

An error occurs in this code, it swears "__clone method called on non-object", $query should have an object, and thanks to "->all()" I have an array there. If we remove "->all()", then it cannot find the field from the photo table. Tell me, please, how to implement it correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2019-05-03
@webinar

1. Of course, all() must be removed, right here:
Must have yii\db\Query or AR object. Where is he from anyway?
2. join should not affect pagination in any way, since pagination will be for Album, and not for attached data, even if you add a million of them. The point is that you are trying to clone something that cannot be cloned:
https://www.php.net/manual/ru/language.oop5.cloning.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question