Mysql 高级加入 laravel 5.2

Mysql advanced joins in laravel 5.2

我有三个 tables:posts,评论和回复

这是我试过的::

$RC = DB::table('comments')
    ->join('replies','comments.reply_id','=','replies.id')
    ->where('comments.handle',$request->handle)
    ->where('replies.handle','!=',$request->handle)
    ->groupBy('replies.post_id')
    ->get(['replies.post_id']);

$PC = DB::table('comments')
    ->join('posts', 'comments.post_id', '=', 'posts.id')
    ->where('comments.handle',$request->handle)
    ->where('posts.handle','!=',$request->handle)
    ->groupBy('comments.post_id')
    ->get(['comments.post_id']);

最后我使用这段代码获得了想要的结果

$res = DB::select("SELECT posts.* FROM posts JOIN replies ON posts.id = replies.post_id 
                    JOIN comments ON posts.id = comments.post_id OR replies.id = comments.reply_id 
                    WHERE comments.handle = $request->handle AND posts.handle != $request->handle 
                    GROUP BY posts.id");

$res1 = DB::table('posts')
    ->join('comments',function ($join){
        $join->on('posts.id','=','comments.post_id')
            ->where('comments.handle','=',$request->handle)
            ->Where('posts.handle','<>',$request->handle);
    })
    ->groupBy('posts.id')
    ->get(['posts.*']);
$results = array_merge($res,$res1);
$results= collect($results);
$results = $results->unique();