Laravel中的多对多多态关系问题

时间:2019-09-09 11:15:56

标签: php laravel eloquent

因此,我一直在从事2种类型的用户注册项目。 1.公司 2.发行人

我已经为这两个模块创建了模块,并且它们都有使用通行证创建的单独的身份验证模块。

一切正常,现在我想添加一个功能,该功能允许从公司向分销商发送消息,反之亦然。

这是我的迁移记录

1。邮件

id

消息

parent_message_id(用于处理消息线程)

2。 fromables(用于处理从哪个用户发送消息的多态关系)

id

message_id

fromable_id

fromable_type('App \ Company'或'App \ Distributor')

3。 toables(处理消息发送给哪个用户的多态关系)

id

message_id

toable_id

toable_type('App \ Company'或'App \ Distributor')

以下是在模型中定义关系的方式:

  1. 公司模型和分销商模型
public function messages_sent()
{
    return $this->morphToMany('App\Message', 'fromable');
}
public function messages_received()
{
    return $this->morphToMany('App\Message', 'toable');
}
  1. 消息模型
public function from_company()
{
    return $this->morphedByMany('App\Company', 'fromable');
}
public function from_distributor()
{
    return $this->morphedByMany('App\Distributor', 'fromable');
}

public function to_company()
{
    return $this->morphedByMany('App\Company', 'toable');
}
public function to_distributor()
{
    return $this->morphedByMany('App\Distributor', 'toable');
}

下面是我如何访问公司和分销商控制人员内部发送和接收的消息。

$user = $request->user();
$messages_received = $user->messages_received;
$messages_sent = $user->messages_sent;

直到现在,这种方法一直很好。

现在的问题是,当我运行以下代码以接收所有消息时, $messages_received = $user->messages_received;

它返回所有消息,但不返回发送消息的人。正式的message_received使用'toable'关系。并且发件人ID在'fromable'关系中。

在这里我不确定在完成后如何获取发件人详细信息以及所有邮件 $ user-> messages_received

我该怎么做? 如果有其他方法可以实现此消息传递系统,请也让我知道。

谢谢。

1 个答案:

答案 0 :(得分:0)

据我了解,您应该能够$user->messages_received->load('from_company')来获取消息发送到的公司的关系。