簡體   English   中英

Laravel中的多對多多態關系問題

[英]Multiple many to many polymorphic relationship problem in Laravel

因此,我一直在從事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后如何獲取發件人詳細信息以及所有消息的地方

我怎樣才能做到這一點? 如果有任何其他方法可以實現此消息傳遞系統,請也讓我知道。

謝謝。

據我了解,您應該能夠執行$user->messages_received->load('from_company')來獲得與發送消息的公司的關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM