Use Has Many Relations with Yii2 GridView

In Yii2 it is very easy to display has many relations for an ActiveRecord with the GridView. This tutorial is aimed to explain how easy it is to display your has many relations with Yii2 GridView in your Yii2 application.

For this tutorial I uses two model classes, User and Post. Here is the table structure for my models.

Then I created the model class using the yii2 gii code generator. In the User model class I had defined relation to Post model as follows

This relation defines that User is having a has many relation to Post based on the userID attribute of Post and id attribute of User.

Now we have the relation defined in the model and we are good to use it in the GridView. To show the posts for a given User I have created a new action named ‘posts’ in the UserController with an argument ‘$userID‘.

First we are loading the ActiveRecord for the user with the given $userID. Then as usual we are passing that ActiveRecord to the view file ‘posts’.

Now add the following lines to the posts view file.

Here we can see we are generating an ActiveDataProvider with its ‘query’ argument populated with the relation. This is all what we have to do to get all the posts for the given User and generate the ActiveDataProvider to populate the GridView with the relation.

Here is the resulting GridView

Let me know if you are having any queries regarding the tutorial. Happy coding.

Using CArrayDataProvider with CGridView and Sorting

CGridView is a very handy widget from Yii framework for displaying tabular data. Usually we use CActiveDataProvider with CGridView to display records from database in the site. But at time we might need to display custom generated data in tables. CArrayDataProvider helps us to use CGridView with a normal array of data same as we use with CActiveDataProvider. This article helps you in using CArrayDataProvider with CGridView and also enable the sorting feature on the CGridView.

Preparing CArrayDataProvider

Controller Action


Rendering the CGridView

Rendering part is same as it is with the CActiveDataProvider. Only thing to worry is about setting the header of each column as the array doesn’t provide them.

View File (arrayDP.php)


Used CArrayDataProvider with CGridView Sorted with Age Field
Used CArrayDataProvider with CGridView Sorted with Age Field

Hope this article helped you to understand how to use CArrayDataProvider with CGridView. If you are having any doubts please feel free to comment.