Answer the question
In order to leave comments, you need to log in
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']);
}
$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
Controller
public function actionView($id)
{
$model = Home::findOne($id);
$dataProvider = new ActiveDataProvider([
'query' => $model->getNews(),
]);
return $this->render('view', [
'model' => $model,
'dataProvider' => $dataProvider,
]);
}
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_one_news_page_template',
]);
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 questionAsk a Question
731 491 924 answers to any question