Laravel relation many to many with additional pivot

只愿长相守 提交于 2019-12-13 02:56:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30982382/laravel-relation-many-to-many-with-additional-pivot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!