Displaying and filtering ActiveRecord relational data in a grid's column

Let's now focus on relational data in GridView, a common topic that is easily solved by itself.

Think about the reservations grid, which has two relational fields: room_id and customer_id, referring respectively to room and customer tables. What if we want to immediately display the customer's surname, or room number?

At this point, our goal is to display relational data, for example, the customer's surname instead of customer_id in GridView. Fields that refer to related data are expressed with the relation attribute.

In the reservation grid view, customer is the relation to get a related customer and surname is the field to keep.

Therefore, to display the customer's surname, ...

Get Yii2 By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.