[英]Laravel With and wherePivot
I'm trying to extract all companies and contacts with pivot.main_contact = 1. 我正在尝试使用pivot.main_contact = 1提取所有公司和联系人。
Tables: 表:
Company: id, name
Company_contacts: id, company_id, contact_id, main_contact
Contacts: id, name
Model: 模型:
class Company extends Model
{
public function mainContact()
{
return $this->belongsToMany('App\Contact', 'company_contacts')
->wherePivot('main_contact', '=', 1);
}
}
Controller: 控制器:
$query = Company::with('mainContact')->get();
This returns companies + ALL contacts for the companies and NOT ONLY the ones with main_contact = 1. 这将返回公司的公司+所有联系人,而不仅仅是main_contact = 1的公司。
Try to add withPivot()
: 尝试添加
withPivot()
:
return $this->belongsToMany('App\Contact', 'company_contacts')
->withPivot('main_contact')
->wherePivot('main_contact', '=', 1);
Company::with('mainContact')->get();
returns all compaines and all contacts. 返回所有公司和所有联系人。 You should be doing
$company->mainContacts()->get();
你应该做
$company->mainContacts()->get();
instead. 代替。
$companies=Company::all();
foreach($companies as $company)
{
print_r($company->mainContact()->get());
}
die;
First, for reasons I'm unsure of, you need to add withPivot('main_contact');
首先,由于我不确定的原因,你需要添加
withPivot('main_contact');
to your relation. 你的关系 This will return
main_contact
in your collection under pivot
这将在
pivot
下返回main_contact
中的main_contact
class Company extends Model
{
public function mainContact()
{
return $this->belongsToMany('App\Contact', 'company_contacts')
->withPivot('main_contact');
}
}
The second thing you need to do is use withPivot()
while constraint eager loading like so: 你需要做的第二件事是使用
withPivot()
而约束渴望加载,如下所示:
$companies = Company::with(['mainContact'=> function($query){
$query->wherePivot('main_contact', 1);
}])->get();
I've checked it, it works. 我检查过它,它有效。
Just to go a bit above and beyond. 只是稍微超越一点。 Sometimes you'll want to query a pivot table without knowing the value.
有时您需要在不知道值的情况下查询数据透视表。 You can do so by:
你可以这样做:
$companies = Company::with(['mainContact'=> function($query) use ($contact){
$query->wherePivot('main_contact', $contact);
}])->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.