对话列表重复多次相同的名称

问题描述:

这里是我的消息控制器的代码。在消息中心,我已经离开了显示对话列表的列。问题是,如果用户从同一个发件人收到多封邮件,那么在对话列表中将多次使用相同的发件人姓名(请参见下图),我想在对话中使用相同的发件人姓名只列出一次。对话列表重复多次相同的名称

// 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

劳克感谢您的评论,我很感激。你能否稍微解释一下,或者添加你想法的代码。谢谢 –

如果你想从发信人的名字的最后一个消息尝试使用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必须是用户表的外键。但你可以让它保持原样。我认为在这种情况下并不重要 –