根据可互换顺序的两个键过滤记录
Filter out Records Based on Two Keys of Interchangeable Order
我正在为客户项目的一部分创建私人消息传递系统。
我将每条消息存储为一条记录,其中 from
的值作为发送者的 ID,to
作为接收者的 ID,message
作为消息文本。
我想要一个页面,用户可以在其中查看与他们有消息传递线程的其他用户的列表。我正在检索用户是发送者或接收者的所有相关消息:
$thisProfile = Auth::user()->profile_id;
$messages = DB::table('messages')
->where('from', '=', $thisProfile)
->orWhere('to', '=', $thisProfile)
->get();
return view('messages.all', compact('messages'));
但是,这显然是返回提及相同两个用户的记录。以下是我以用户 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
我想过滤掉之前检索过相同两个用户的记录。在这种情况下,结果应如下所示:
#1 - from: 1, to: 2
#4 - from: 4, to: 1
#6 - from: 9, to: 1
我得到的最接近的是找到用于集合的 unique()
方法,它按顺序过滤掉 to
或 from
的记录。
如何根据两个键 to
和 from
过滤掉记录,它们的顺序可以互换?
我想我终于明白你在做什么了,这就是我建议你做的。
预计您对 messagesFrom
(用户发送的)和 messagesTo
(他们收到的)有单独的关系,您应该能够使用此查询:
$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();
加载最新的 Message
对话进行预览也是一件好事,但这听起来足以解决其他问题。
我正在为客户项目的一部分创建私人消息传递系统。
我将每条消息存储为一条记录,其中 from
的值作为发送者的 ID,to
作为接收者的 ID,message
作为消息文本。
我想要一个页面,用户可以在其中查看与他们有消息传递线程的其他用户的列表。我正在检索用户是发送者或接收者的所有相关消息:
$thisProfile = Auth::user()->profile_id;
$messages = DB::table('messages')
->where('from', '=', $thisProfile)
->orWhere('to', '=', $thisProfile)
->get();
return view('messages.all', compact('messages'));
但是,这显然是返回提及相同两个用户的记录。以下是我以用户 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
我想过滤掉之前检索过相同两个用户的记录。在这种情况下,结果应如下所示:
#1 - from: 1, to: 2
#4 - from: 4, to: 1
#6 - from: 9, to: 1
我得到的最接近的是找到用于集合的 unique()
方法,它按顺序过滤掉 to
或 from
的记录。
如何根据两个键 to
和 from
过滤掉记录,它们的顺序可以互换?
我想我终于明白你在做什么了,这就是我建议你做的。
预计您对 messagesFrom
(用户发送的)和 messagesTo
(他们收到的)有单独的关系,您应该能够使用此查询:
$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();
加载最新的 Message
对话进行预览也是一件好事,但这听起来足以解决其他问题。