Laravel与其他枢纽之间的多对多关系 [英] Laravel relation many to many with additional pivot

查看:82
本文介绍了Laravel与其他枢纽之间的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

状态更新

我已经实现了多种关系类型的变体,但是如何插入addition字段?

I have implemented morph to many relationship type but how can I insert into the addition field?

多态关系的代码为:

public function mailmessages()
{
    return $this->morphToMany('Mailmessage','rel','mailmessage_rels','rel_id','mailmessage_rel_id')
                ->withPivot(['addition']);
}

原始帖子

我有一个Laravel项目,它使用了许多对许多关系,并且在数据透视表中,我还有一个描述相关模型的字段. 例如,我有此邮件模型,这是关系表mailmessage_rels,这里是简要概述:

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)     |
+--------------------+------------------+

让我们说我有一个Contact模型.在此联系模型中,我具有mailmessages关系.

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']);
    }

当我检索信息时一切正常,但是当我尝试创建一个关系(使用attach)时,它没有写出实际上不是我想要的rel_type字段.我简单地使用:

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.

这篇关于Laravel与其他枢纽之间的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆