在laravel 4.2中,加入查询无法正常工作

时间:2014-12-03 06:34:58

标签: jquery join laravel left-join

我正在使用laravel 4.2。当我运行此Left Join查询时,

$data = DB::table('posts')
        -> leftJoin('users','posts.user_id','=','users.id')
        -> where('posts.id',$id)
        -> select('posts.id as post_id,posts.title as title,users.firstname as fname')
        -> first();

当我打印$data得到结果时,

stdClass Object(
   [post_id,posts.title] => 5
)

这不是预期的答案。我希望答案如下,

stdClass Object(
  [post_id] => 2
  [title] => Test3
  [fname] => myname
)

如何获得正确的结果?这个查询有什么问题吗?

2 个答案:

答案 0 :(得分:2)

更改选择

  $data = DB::table('posts')
            -> leftJoin('users','posts.user_id','=','users.id')
            -> where('posts.id',$id)
            -> select('posts.id as post_id','posts.title as title','users.firstname as fname')
            -> first();

答案 1 :(得分:0)

$data = DB::table('posts')
    -> select('posts.id,users.id,posts.title users.firstname')
    -> leftJoin('users','posts.user_id','=','users.id')
    -> where('posts.id',$id)
    -> first();

这应该给你合适的结果