基于可互换顺序的两个键过滤掉记录

问题描述:

I am creating a private messaging system for part of a client project.

I am storing each message as a record with the values for from as the ID of the sender, to as the ID of the receiver, and message as the message text.

I would like to have a page in which users can view a list of other users that they have a messaging thread with. I am retrieving all relevant messages that the user is a sender or receiver of:

$thisProfile = Auth::user()->profile_id;

$messages = DB::table('messages')
    ->where('from', '=', $thisProfile)
    ->orWhere('to', '=', $thisProfile)
    ->get();

return view('messages.all', compact('messages'));

However, that is obviously returning records where the same two users are mentioned. Below are some example records that I am getting when logged in as user 1:

#1 - from: 1, to: 2
#2 - from: 2, to: 1
#3 - from: 1, to: 2
#4 - from: 4, to: 1
#5 - from: 1, to: 4
#6 - from: 9, to: 1

I would like to filter out the records where the same two users have been retrieved before. In this case, the results should look like:

#1 - from: 1, to: 2
#4 - from: 4, to: 1
#6 - from: 9, to: 1

The closest I have got is finding the unique() method used with collections, which filters out records for either to or from in one order.

How can I filter out records, based on the two keys to and from, where they are of interchangeable order?

我正在为客户项目的一部分创建一个私人消息系统。 p>

我将每条消息存储为记录,其中来自 code>的值为发送方的ID,为 code>作为接收方的ID,以及消息 代码>作为消息文本。 p>

我希望有一个页面,用户可以在其中查看他们拥有消息传递线程的其他用户的列表。 我正在检索用户是发送者或接收者的所有相关消息: p>

  $ thisProfile = Auth :: user() - > profile_id; 
 
 $ messages  = DB :: table('messages')
  - > where('from','=',$ thisProfile)
  - > orWhere('to','=',$ thisProfile)
  - &gt  ; get(); 
 
return view('messages.all',compact('messages')); 
  code>  pre> 
 
 

但是,这显然是返回记录的地方 提到了相同的两个用户。 下面是我以用户1登录时获得的一些示例记录: p>

 #1  -  from:1,to:2 
#2  -  from:2,to  :1 
#3  - 从:1,到:2 
#4  - 从:4,到:1 
#5  - 从:1,到:4 
#6  - 从:9,到:1  
  code>  pre> 
 
 

我想过滤掉以前检索过两个用户的记录。 在这种情况下,结果应如下所示: p>

 #1  -  from:1,to:2 
#4  -  from:4,to:1 
#6  - 从:9,到:1 
  code>  pre> 
 
 

我最接近的是找到与集合一起使用的 unique() code>方法, 在一个订单中输出到 code>或的 code>的记录。 p>

如何基于两个键 code>和来自 code>,它们是可互换的顺序? p> div>

I think that I finally understood what you are up to and this is what I would suggest you to do.

Expecting that you have separate relations for messagesFrom (the ones the user sent) and messagesTo (the ones they received), you should be able to use this query:

$thisProfile = Auth::user()->profile_id;

$users = User::whereHas('messagesFrom', function ($messages) use ($thisProfile) {
        $messages->where('to', $thisProfile);
    })
    ->orWhereHas('messagesTo', function ($messages) use ($thisProfile) {
        $messages->where('from', $thisProfile);
    })
    ->get();

Loading the latest Message of a conversation for a preview could be a neat thing as well, but this sounds like it was enough for a whole other question.