2017-06-15 46 views
-1

我已经follwoing查询laravel LEFT JOIN查询不工作

$data=Post::join('category', 'questions.categoryid', '=', 'category.CategoryId') 
     ->where('category.CategoryName','demo') 
     ->join('comments', function ($join) { 
       $join->on('posts.postId', '=', 'comments.postId') 
       ->where('posts.postId', '!=', 'comments.linkId'); 
     }) ->get(); 

我上面的查询我在哪里retireveing基于类别名称所有发布和与评论

每一个想工作正常,但下加入表线无法正常工作。我的意思是,即使添加此行仍是其retriving所有记录,甚至我试图!=<>但不工作

->where('posts.postId', '!=', 'comments.linkId'); 
+1

希望你知道这是不是一个左连接。 Laravel的连接是一个内部连接。 – Devon

回答

2

不要使用WHERE内的条款JOIN,可以延长ON子句:

->join('comments', function ($join) { 
     $join->on('posts.postId', '=', 'comments.postId') 
      ->on('posts.postId', '!=', 'comments.linkId'); 
}) 

这将等同于:

JOIN comments ON posts.postId = comments.postId AND posts.postId != comments.linkId 
+0

@ devon.Thanks我试过这一个。如果我添加像这样然后即时只获得一个记录,其中有评论.linkId – vision

+0

@ devon.even我改变了左边加入,然后它会回顾所有 – vision

+0

我不确定是什么你在这之后,但它不再是听起来像Laravel问题,也许你只是不理解左连接和内连接做什么?也许你想看看雄辩的关系呢? – Devon