Laravel:Join Query中的用户定义对象名称

时间:2014-12-13 11:26:06

标签: php mysql laravel-4

我在Laravel中编写了一个成功返回的连接查询。我现在正在尝试将对象名称添加到返回的值,就像从表中返回一样。

Laravel查询

$post = DB::table('follow')
    ->join('posts', 'follow.user2', '=', 'posts.userid')
    ->where('follow.user1',Auth::user()->id)
    ->where('follow.user2','!=',Auth::user()->id)
    ->where('posts.created_at','>',$update)
    ->select('posts.created_at', 'posts.userid')
    ->orderBy('posts.created_at','desc')
    ->get();

以上查询返回以下内容

array (size=1)
0 => 
  object(stdClass)[208]
    public 'created_at' => int 1418466963
    public 'userid' => int 5

我想要实现的是以下输出

array (size=1)
0 => 
  object(stdClass)[208]
    public 'created_at' => int 1418466963
    public 'userid' => int 5
    public 'oType' => string 'post'  //This is user defined.

我尝试的是(显然是错的,但只是暗示我在尝试什么)

$post = DB::table('follow')
    ->join('posts', 'follow.user2', '=', 'posts.userid')
    ->where('follow.user1',Auth::user()->id)
    ->where('follow.user2','!=',Auth::user()->id)
    ->where('posts.created_at','>',$update)
    ->select('posts.created_at', 'posts.userid', 'oType as post') //Compare this line with 1st query
    ->orderBy('posts.created_at','desc')
    ->get();

1 个答案:

答案 0 :(得分:1)

您可以使用DB :: raw()来实现此目的。

->select('posts.created_at', 'posts.userid', DB::raw('\'post\' as oType'))