试图在 Laravel 5.4 中建立一对多的关系。我已经在线阅读了文档和其他资源,但在每种情况下都无法使其正常工作,并且我尝试过的各种方法都会导致不同的错误。
我有以下三个表:
我正在努力使该帐户可以(但不一定)拥有一个或多个联系人。
我的模型如下:
帐号
public function contacts()
{
return $this->hasMany(Contact::class);
}
联系方式
public function account()
{
return $this->belongsTo(Account::class)->withPivot('primary', 'billing');
}
然后在 Controller 中说我尝试:
$account = Account::find($id);
if($account->isEmpty())
return response()->json(['Account not found.'], 404);
$contact = $account->contacts()->exists();
我收到以下错误:
(1/1) BadMethodCallException
方法联系人不存在。
显然,我想要做的就是在建立联系时,通过数据透视表将其附加到帐户。
在获取帐户时,我可以通过数据透视表获取额外的数据透视表字段以及属于该帐户的联系人。
只是为了进一步澄清一点,我试图使用 eloquent,使用枢轴来执行以下查询,而不必在每个实例中都将其写出来。
$contacts = DB::table('account_contact')
->select('contact_id', 'primary', 'billing')
->where('account_id', $id)
->get();
$accountContacts = [];
foreach($contacts as $c){
$accountContact = Contact::find($c->id);
$accountContacts[] = array(
"id" => $accountContact->id,
"sal" => $sal = $accountContact->salutation == null? '' : $accountContact->salutation,
"firstName" => $accountContact->first_name,
"lastName" => $accountContact->last_name,
);
}
我希望能够做类似的事情
$accounts->pivot->contacts
并得到一个像这样的名字:
$accounts->pivot->contacts->first_name
最佳答案
你们的关系是多对多的,所以你需要这样做:
帐号
public function contacts()
{
return $this->belongsToMany(Contact::class)->withPivot('primary', 'billing');
}
联系方式
public function account()
{
return $this->belongsToMany(Account::class)->withPivot('primary', 'billing');
}
那么你应该通过 eloquent 一路做到这一点,以避免 N+1 issue
$account = Account::with("contacts")->where("id", $id)->get();
foreach ($account->contacts as $contact) {
$accountContacts[] = array(
"id" => $accountContact->id,
"sal" => $sal = $accountContact->salutation == null? '' :
$accountContact->salutation,
"firstName" => $accountContact->first_name,
"lastName" => $accountContact->last_name,
);
}
关于php - Laravel 一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47166005/