Yii2: Am I able to use multiple models in a search model?

267 Views Asked by At

In Yii2, am I able to include two models (active records) in one search model and display them in a gridview?

For example, I have two tables, "customers", and "customer_contacts".

In my search model I am using Customers as my main model, while I wish to "left join" to CustomerContacts, and eventually display the Customers.name and CustomerContacts.phoneNumber in the gridview (in dataProvider).

Can someone please guide me on this.

Thank.

2

There are 2 best solutions below

0
On

you can do this by applying left-join in searchModel as following

$query = Customers::find();
$query->joinWith('customer-contact');

And also make hasOne relation with CustomerContact in Customer.php

0
On

Option 1: In the customer model add this function:

Public function getCustomerContact(){
Return $this-> hasOne( CustomerContact::className,[customer_id,id]);

}

Then in your grid view you can easily reference the contact as follows:

customerContact.name

Note that this will only work if there is a one to one relationship between the tables

Option 2: (faster but more challenges)

In the data provider, use a query rather than a model ie $query = new \yii\db\Query();

You can then do all joins etc in the data provider. It is much faster but it requires a little more know-how