D
D
Dmitry Kuznetsov2017-10-16 15:10:04
Laravel
Dmitry Kuznetsov, 2017-10-16 15:10:04

Lazy eager loading and pagination, how to use them all together?

There is some code that, through "eager loading", I load 2 tables from the database ... in short, I can’t explain properly, so I’ll show the code:
General model for loading all data :

$game = Games::getGame($gameName);

    if($game){
      $game->load('getNewsGame');
    }

    return $game;

News model :
/* Получение новостей игры (upd) */
  public function getNewsGame(){
    return $this->hasOne(News::class, 'game_news', 'id_games');
  }

The model of the game itself :
/* Получение данных об игре */
  public function getGame($gameName){
    $getCollectionGames = AllGame::getCollectionGames($gameName);

    return view('Games.getGame', ['games' => $getCollectionGames]);
  }

And in the end I get the game itself and dependencies -> news, etc. and I can use them normally. But the number of news and other databases can have a large number of entries, so pagination is needed. But if you use such a system (another system for obtaining data will not work), then you cannot use (maybe I just don’t know about another way) pagination. Please tell me how can I solve this problem. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kuznetsov, 2017-10-16
@dima9595

I solved the issue with the following crutch:
Data loading model :

public static function getCollectionGames(string $gameName){
    $game = Games::getGame($gameName);   // Получаем данные об игре

                // "Делаем ленивую нетерпеливую загрузку"
    if($game){
      $game->load(['getNewsGame' => function($news){
                                // Добавляем сортировку и даём скрипту вывести на страницу только 10 новостей.
        $news->orderBy('id_news', 'desc')->paginate(10);
      }]);
    }

    return $game;    // Отдаём эти данные
  }

I added a load wrapper and added paginate(10) to display only 10 news items.
In the template : Through $games->getNewsGame() I got all the news. I added paginate(10) so that pagination would start working, as if I were making a new request (I don’t know exactly about this, I didn’t look at the debug. Perhaps, indeed, 1 more request is being made). Well, at the end I add links() to display the pagination itself.

Z
zorca, 2017-10-16
@zorca

Read the docs: https://laravel.com/docs/5.5/pagination#paginating...

A
Alexander Gontarev, 2017-10-16
@igontarev

there is already a built-in method for pagination
https://laravel.com/docs/5.5/pagination#basic-usage

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question