2017-10-29 51 views
0

這裏是我的消息控制器的代碼。在消息中心,我已經離開了顯示對話列表的列。問題是,如果用戶從同一個發件人收到多封郵件,那麼在對話列表中將多次使用相同的發件人姓名(請參見下圖),我想在對話中使用相同的發件人姓名只列出一次。對話列表重複多次相同的名稱

// get recent messages to show in left column 
    $recent = Message::find() 
      ->with('sentFrom') 
      ->where(['sent_to' => Yii::$app->user->identity->id]) 
      ->andfilterWhere([ 
       'or', 
       ['like', 'subject', $search_subject], 
       ['like', 'sent_from', $search_sender], 
       ]) 
      ->orderBy('created_at DESC') 
      ->limit(Yii::$app->params['message_chat']['recent_limit']) 
      ->all(); 
+0

我不知道yii,但總的來說,解決方案是讓你跟蹤最後一條消息的發送者(無論是輸入還是輸出)。如果它們相同,則避免打印消息名稱/頭像的發件人。 – Jauch

+0

繼續Jauch的評論,考慮添加你的視圖的文件代碼 - 我相信你有一個循環打印鏈中的所有消息。 –

+0

勞克感謝您的評論,我很感激。你能否稍微解釋一下,或者添加你想法的代碼。謝謝 –

回答

0

如果你想從發信人的名字的最後一個消息嘗試使用groupBy語句進行yii2 query

$recent = Message::find() 
      ->with('sentFrom') 
      ->where(['sent_to' => Yii::$app->user->identity->id]) 
      ->andfilterWhere([ 
       'or', 
       ['like', 'subject', $search_subject], 
       ['like', 'sent_from', $search_sender], 
       ]) 
      ->orderBy('created_at DESC') 
      ->grouoBy([tablne_name.primaryKey])  
      ->limit(Yii::$app->params['message_chat']['recent_limit']) 
      ->all(); 

其中:

table_name - the mane of table used in sentFrom relation 
primaryKey - the primary key of table_name or something other 
      unique, in your case it's maybe something like sender id 

此查詢將返回所有消息具有唯一的primaryKey值。

+0

b.tokman,謝謝你的回答。我很感激。我已經添加到我的問題數據庫中的消息列表。正如你可能看到「sent_from」是索引,「id」是主要的。你認爲我應該從ID中刪除主鍵並將其提供給「sent_from」? –

+0

不,理想的 - sent_from必須是用戶表的外鍵。但你可以讓它保持原樣。我認爲在這種情況下並不重要 –