Search code examples
mysqllaraveleloquent-relationship

Laravel Relation belongTo whereHas


i have google for 2 days almost and i can't find where i am missing

My goal is From the table Customers get the contacts from the table Customers_Contacts for that i have this 2 relations:

My Customers model:

class Customers extends Model{
   protected $table = 'customers';

   public function customerscontacts(){
    return $this->hasMany('App\Models\CustomersContacts', 'id_customer', 'id');
   }
}

My CustomersContacts model:

class CustomersContacts extends Model{
 protected $table = 'customers_contacts';
    
    public function Customers(){
     return $this->belongsTo('App\Models\Customers', 'id', 'id_customer');
    }

}

My query:

$data = Customers::where(function ($query) use ($searchNome) {
                            foreach ($searchNome as $value) {
                                $query->WhereRaw("UPPER(nome) LIKE '%{$value}%'");
                            }
                        });
                        
    if($email){   $data = $data->whereHas('customerscontacts', function($query) use($email) {
                             $query->whereRaw("UPPER(contact) = '{$email}'")->where('type','email');
            });}
            
     if($contacto){   $data = $data->whereHas('customerscontacts', function($query) use($contacto) {
                             $query->where('contact',$contacto)->orwhere('contact',$contacto)->where('type','!=','email');
    });}

$data = $data->get();

This code is searching and getting the results from the table Customers, but the results don't show the table customers_contacts. Sorry i am new with relations in laravel.

Thanks for help.


Solution

  • first of all .. you should fix the relation:

     public function Customers(){
         return $this->belongsTo('App\Models\Customers','id_customer');
        }
    

    the second argument for belongsTo relation must be the foreign key like in doc

    then to load customers_contacts you can use eager loading

    $data = Customers::with('customerscontacts')->where(function ($query) use ($searchNome) {
                                foreach ($searchNome as $value) {
                                    $query->WhereRaw("UPPER(nome) LIKE '%{$value}%'");
                                }
                            });
    // ........
    

    now inside $data you will got a collection of Customers, and inside every one of 'Customers' you should find another collection 'customerscontacts' ..