我正在用Laravel创建一个消息服务。
我想根据时间显示所有人最近的消息。这就是我想要实现的
下面是我的桌子
消息表
消息用户表
我试过下面的代码
SELECT DISTINCT user_id,sender
FROM (
SELECT DISTINCT message_user.user_id, messages.sender, messages.created_at
FROM messages
JOIN message_user ON message_user.message_id=messages.id AND message_user.user_id=225
UNION
SELECT DISTINCT message_user.user_id, messages.sender, messages.created_at FROM messages
JOIN message_user ON message_user.message_id=messages.id AND messages.sender=225 AND message_user.user_id NOT IN (
SELECT DISTINCT messages.sender
FROM messages
JOIN message_user ON message_user.message_id=messages.id AND message_user.user_id=225
)
) mytable
ORDER BY created_at
问题是输出的格式不符合预期(未根据创建的格式进行排序)
下面是我尝试过的相应的Laravel代码
$id = $request->user()->id;
$user = User::find($id);
$buddylist = $user->messages()->select(DB::raw('message_user.user_id,messages.sender,messages.created_at'));
$subquery = Message::select(DB::raw(' messages.sender'))->join('message_user','messages.id','=','message_user.message_id') ->where("message_user.user_id",'=',$request->user()->id);
$mybuddy = Message::selectRaw('message_user.user_id,messages.sender,messages.created_at')
->join('message_user','messages.id','=','message_user.message_id')
->where("messages.sender",'=',$request->user()->id)
->whereNotIn('message_user.user_id', $subquery)
->union( $buddylist)
->groupBy('sender')
->groupBy('user_id')
->orderBy('created_at','desc')
->get();
最佳答案
如果您有另一个名为“receiver_id”的列,则可以执行以下操作:
$query="select * from messages WHERE sender_id='user_id' or receiver_id='user_id' ORDER BY created_at asc";
关于php - 用于创建消息列表的SQL查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53995311/