2014-12-13 58 views
0

我有成功地返回在Laravel中寫入的聯接查詢。我現在試圖將對象名添加到返回的值,就好像它從表中返回一樣。Laravel:在Join Query中用戶定義的對象名稱

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

您可以通過使用DB :: raw()來實現此目的。

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

Laravel拋出錯誤 '語法錯誤,意外 ':'''在DB:原料( '\' 後\ '作爲oType')' – 2014-12-13 12:03:04

+0

對不起,應該是DB ::生的,不是DB :生的。更正了答案。 – 2014-12-13 12:05:21

+0

哦,即使我不在乎:p工作正常..謝謝 – 2014-12-13 12:06:08