dongmu2517 2015-06-22 14:22
浏览 34
已采纳

Laravel与许多人有很多关系

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条回答 默认 最新

  • douliedu335997 2015-06-23 08:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解