当HasMany关系也存在于同一模型中时,如何更新HasOne关系? [英] How to update a HasOne relationship when a HasMany relationship also exists with the same model?
问题描述
我正试图在Eloquent中定义两个相同模型之间的两者的HasMany和HasOne关系.
I'm trying to define both a HasMany and HasOne relationship between the same two models in Eloquent.
我的Organization
类有很多Contact
:
public function contacts()
{
return $this->hasMany(Contact::class);
}
同样,我的Contact
类反映了这种关系:
And likewise, my Contact
class reflects this relationship:
public function organization()
{
return $this->belongsTo(Organization::class);
}
但是,每个Organization
都只有一个主要" Contact
.我正在使用表格列organizations.primary_contact_id
来标识哪个:
But also, each Organization
has exactly one "primary" Contact
. I am using a table column organizations.primary_contact_id
to identify which one:
public function primaryContact()
{
return $this->hasOne(Contact::class, 'id', 'primary_contact_id');
}
从这里开始,我被困住了. Contact
中的反向关系已经存在,所以我写了另一个我认为可以解决问题的函数,以判断是否更新了父表中的值,由于定义了这种关系,Eloquent会自然地获取contacts表中的对应记录:
From here, I'm stuck. The reverse relationship in Contact
already exists, so I wrote another function I thought would do the trick, figuring if I updated the value in the parent table, Eloquent would naturally fetch the corresponding record in the contacts table since I defined the relationship:
/**
* @param \App\Contact
*/
public function setPrimaryContact($contact)
{
$this->primary_contact_id = $contact->id;
$this->save;
}
但不是:
>>> $org = Organization::find(17)
=> App\Organization {#2923
id: 17,
name: "Test Org",
primary_contact_id: 33,
}
>>> $alice= $org->primaryContact
=> App\Contact {#2938
id: 33,
organization_id: 17,
fname: "Alice",
lname: "Abbot",
}
>>> $bob = Contact::find(34)
=> App\Contact {#2939
id: 34,
organization_id: 17,
fname: "Bob",
lname: "Baker",
}
>>> $org->setPrimaryContact($bob)
=> null
>>> $org
=> App\Organization {#2923
id: 17,
name: "Test Org",
primary_contact_id: 34,
primaryContact: App\Contact {#2938
id: 33,
organization_id: 17,
fname: "Alice",
lname: "Abbot",
},
}
您可以看到setPrimaryContact($bob)
执行得很好,因为primary_contact_id
已更新为鲍勃的id
,但primaryContact
仍列出了爱丽丝.
You can see setPrimaryContact($bob)
executed fine, as primary_contact_id
got updated to Bob's id
, but primaryContact
still lists Alice.
为什么primaryContact
不返回正确的对象?
Why is primaryContact
not returning the correct object?
推荐答案
- 您的
setPrimaryContact
方法不会更新您的表,因为您调用的是$this->save
而不是$this->save()
,save
是方法 - 在
$org->setPrimaryContact($bob)
之后,您应该调用$org-> primaryContact->refresh()
以获得更新的记录. - Your
setPrimaryContact
method won't update your table, because you call$this->save
, not$this->save()
,save
is a method - After
$org->setPrimaryContact($bob)
, you should call$org-> primaryContact->refresh()
to get the updated record.
这篇关于当HasMany关系也存在于同一模型中时,如何更新HasOne关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!