Status Update
I have implemented morph to many relationship type but how can I insert into the addition
field?
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. For example I have this mail message Model and this is the relation table mailmessage_rels
Here is a brief overview:
+--------------------+------------------+
| 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. In this Contact model I have mailmessages
relation.
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.