show column from foreign table in index action


in my yii2 app I need to create a list view (for example a list of elements from model "invoices") and in that list, show along with normal table fields a field from a foreign table (for example joining together 2 tables with a leftJoin).

For example I create a table "clients" and a table "invoices", in the invoices list I need to show the name of the clients and not the clients id.

Someone can help me?

Thank you very much


Create a relation from invoice and client.

Thank you for your reply.

I’ve created the methods that call hasOne() and hasMany() in each model . But how can I show foreign data in a GridView::widget ?

Thank you


in GridView columns, use as ‘name’ field ‘relation.attribute’.

So if your relation is B_to_A and field to display is field_to_display, ‘name’ attribute of GridView column is:

[ 'name' => 'B_to_A.field_to_display' ]

You could also write:

[ 'value' => function($data) { return $data->B_to_A.field_to_display; } ]

But if you don’t specify ‘name’ attribute of GridView column, filter won’t display.