[英]Laravel relation many to many with additional pivot
Status Update 状态更新
I have implemented morph to many relationship type but how can I insert into the addition
field? 我已将morph实现为许多关系类型,但是如何插入
addition
字段?
The code for the polymorphic relation is: 多态关系的代码为:
public function mailmessages()
{
return $this->morphToMany('Mailmessage','rel','mailmessage_rels','rel_id','mailmessage_rel_id')
->withPivot(['addition']);
}
Original Post 原始帖子
I have a Laravel project that uses many to many relations and in the pivot table I have additional field that describes the related model. 我有一个Laravel项目,它使用了许多对许多关系,并且在数据透视表中,我还有一个描述相关模型的字段。 For example I have this mail message Model and this is the relation table
mailmessage_rels
Here is a brief overview: 例如,我有此邮件模型,这是关系表
mailmessage_rels
这里是简要概述:
+--------------------+------------------+
| Field | Type |
+--------------------+------------------+
| id | int(10) unsigned |
| mailmessage_rel_id | int(10) unsigned |
| rel_id | varchar(36) |
| rel_type | varchar(36) |
| addition | varchar(255) |
+--------------------+------------------+
Lets say I have a Contact model. 可以说我有一个Contact模型。 In this Contact model I have
mailmessages
relation. 在此联系模型中,我具有
mailmessages
关系。
public function mailmessages()
{
return $this->belongsToMany('Mailmessage','mailmessage_rels','rel_id','mailmessage_rel_id')
->wherePivot('rel_type','Contact')
->withPivot(['addition']);
}
When I retrive information everything is OK, but when I try to create a relation(using attach) it does not write the rel_type
field which actually is not what I want. 当我检索信息时一切正常,但是当我尝试创建一个关系(使用attach)时,它没有写
rel_type
字段,而这实际上并不是我想要的。 I use simply: 我简单地使用:
$contact->mailmessages()->attach($message);
Should I do the attachment manually or should I add some additional parameter to the code? 我应该手动执行附件还是应该在代码中添加一些其他参数?
As per your requirement, I blieve you have to update your relation to Polymorphic Relations. 根据您的要求,我相信您必须更新与多态关系的关系。 and than to access other attributes try one of them method.
而不是访问其他属性,请尝试其中一种方法。
$user->roles()->attach(1, ['expires' => $expires]);
$user->roles()->sync([1 => ['expires' => true]]);
User::find(1)->roles()->save($role, ['expires' => $expires]);
If you still facing some dificulties to handle that requirement let me know. 如果您仍然面临一些困难,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.