show column from foreign table in index action

Hello,

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

Alessandro

Create a relation from invoice and client.

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#working-with-relational-data

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

Ale

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.