Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过连接两个表而无雄辩关系的Laravel Order_Laravel_Laravel Query Builder - Fatal编程技术网

通过连接两个表而无雄辩关系的Laravel Order

通过连接两个表而无雄辩关系的Laravel Order,laravel,laravel-query-builder,Laravel,Laravel Query Builder,我有两张桌子可以用来聊天 “用户”表格结构: 身份证件 名称 老实说,我不能确定这是否有效,因为我无法测试它,但我认为代码应该是这样的: $messagesSent = DB::table('messages') ->select('sender_id as other_user', DB::raw('MAX(id) as last_message_id')) ->where('receiver_id', auth()->id()) ->group

我有两张桌子可以用来聊天

“用户”表格结构:

身份证件 名称
老实说,我不能确定这是否有效,因为我无法测试它,但我认为代码应该是这样的:

$messagesSent = DB::table('messages')
    ->select('sender_id as other_user', DB::raw('MAX(id) as last_message_id'))
    ->where('receiver_id', auth()->id())
    ->groupBy('sender_id');

$messagesSentOrReceived = DB::table('messages')
    ->select('receiver_id as other_user', DB::raw('MAX(id) as last_message_id'))
    ->where('sender_id', auth()->id())
    ->groupBy('receiver_id')
    ->union($messagesSent);

$usersWithCommunication = DB::table('users')
    ->select('other_user', DB::raw('MAX(last_message_id) as last_message_id'))
    ->joinSub($messagesSentOrReceived, 'latest_messages', function ($join) {
        $join->on('users.id', '=', 'latest_messages.other_user');
    })
    ->groupBy('other_user');
    

return DB::table('users')
    ->leftJoinSub($usersWithCommunication, 'latest_communications', function ($join) {
        $join->on('users.id', '=', 'latest_communications.other_user');
    })
    ->select('users.*')
    ->orderBy('latest_communications.last_message_id', 'asc')
    ->get();

它将仅显示用户是否存在任何消息。事实上,我希望这些用户在顶部,所有其他用户在之后。你的代码解决了我的排序问题。有了这一点,我还希望其他用户位于底部。谢谢最后我用leftJoinSub解决了return@DebarshiDas编辑了我的答案,以便正确回答问题。我的代码真的没有错误吗?我肯定我会搞砸的,因为我不能真正测试任何东西,我这里有另一个问题!我没有加载所有用户,而是绑定分页。但当我在return方法中使用paginate(10)而不是get()时,我总是得到一个重复的用户和其他9个用户。但是如果我使用get(),那么数组中就没有重复的用户。我想不出问题出在哪里@DebarshiDas如果您创建了新问题,它将是首选。您可以获得更多答案并指定更多信息