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.

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

报告相同问题?

悬赏问题

  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计