代码之家  ›  专栏  ›  技术社区  ›  BCPNAYAK

Mysql advanced加入laravel 5.2

  •  0
  • BCPNAYAK  · 技术社区  · 7 年前

    tables to join

    • 回复表与帖子表相同,但它是对帖子的回复
    • 帖子表有评论
    • 回复表也有评论

    这就是我尝试过的:

    $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']);
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   BCPNAYAK    7 年前

    最后,我使用这段代码来获得期望的结果

    $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();