我用谷歌已经快2天了,我找不到我失踪的地方了
我的目标是从表Customers中获得表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();
这段代码正在搜索并获取来自表Customers的结果,但是结果没有显示表customers_contacts。对不起,我是新来的拉拉维尔亲戚。
谢谢你的帮助。
发布于 2020-07-23 21:37:16
首先..您应该修复关系:
public function Customers(){
return $this->belongsTo('App\Models\Customers','id_customer');
}
与doc中一样,belongsTo关系的第二个参数必须是外键
然后,您可以使用eager loading加载customers_contacts
$data = Customers::with('customerscontacts')->where(function ($query) use ($searchNome) {
foreach ($searchNome as $value) {
$query->WhereRaw("UPPER(nome) LIKE '%{$value}%'");
}
});
// ........
现在在$data中,您将获得一个客户集合,并且在每个“Customers”中,您将找到另一个集合“customerscontacts”。
https://stackoverflow.com/questions/63055346
复制相似问题