P
P
phpForeve2017-04-02 00:29:40
Yii
phpForeve, 2017-04-02 00:29:40

Is it possible to paginate the data that I have included via the hasMany link?

I have 3 tables. "Home", "News" and "News for Home", which links the desired news to a specific home.

public function getNews(){
        return $this->hasMany(News::className(), ['id' => 'news_id'])
        ->viaTable('home_news', ['home_id' => 'id']); 
    }

I do pagination in the following way. The number of pages is considered correct, but the content on any of the pages is displayed in full. How to fix?
$home = $this->findModel($id);
        $pages = new Pagination(['totalCount' => count($home->news), 'pageSize' => Settings::getValue('pageSizeNewsInHome'), 'pageSizeParam' => false]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-04-02
@phpForeve

Controller

public function actionView($id)
    {
$model = Home::findOne($id);
        $dataProvider = new ActiveDataProvider([
            'query' => $model->getNews(),
        ]);
        return $this->render('view', [
            'model' => $model,
            'dataProvider' => $dataProvider,
        ]);
    }

view:
echo ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '_one_news_page_template',
]);

M
mitaichik, 2017-04-02
@mitaichik

Pagination is only responsible for calculating the number of required pages, the current page, the number of required elements per page, etc. It has nothing to do with data.
Here you need to use ActiveDataProvider. It combines pagination, data sampling, and sorting.
And yes, count($home->news) - do you understand how suboptimal this construction is? In general, use ActiveDataProvider - it will do everything right.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question