Laravel 关系 belongsTo whereHas

Laravel Relation belongTo whereHas

我已经 google 快 2 天了,我找不到我失踪的地方

我的目标是从 table 客户获得来自 table Customers_Contacts 的联系人,因为我有这两个关系:

我的客户模型:

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

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

我的 CustomersContacts 模型:

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

}

我的查询:

$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();

此代码正在搜索 table 客户并获取结果,但结果未显示 table customers_contacts。 抱歉,我是 laravel.

的新人

感谢您的帮助。

首先..你应该修正关系:

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

belongsTo 关系的第二个参数必须是外键,如 doc

然后加载 customers_contacts 你可以使用 eager loading

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

现在在 $data 中你会得到一个 Customers 集合,在每个 'Customers' 中你应该找到另一个集合 'customerscontacts' ..