2013-03-01 59 views
2

我想使用關鍵字AS來組合兩列,所以我可以在該列上排序。Laravel Eloquent AS關鍵字

這是完整的查詢,因爲它目前。

$quotes = Quote::where('created_at', '>=', $date) 
     ->where('created_at', '<=', date('Y-m-d').' 23:59:59') 
     ->order_by('upvotes', 'desc') 
     ->paginate(5); 

我願做

->order_by('(downvotes - upvotes) as votes', 'desc') 

謝謝。


解決方案

好像使用DB ::原始()是做它,Laravel /雄辯只是不明白的必經之路。

工作的解決方案是

$quotes = Quote::select(array('id', DB::raw('(downvotes - upvotes) as votes'), 'upvotes', 'downvotes', 'etc')) // Rest of column needed. 
     ->where('created_at', '>=', $date) 
     ->where('created_at', '<=', date('Y-m-d').' 23:59:59') 
     ->order_by('votes', 'asc') 
     ->paginate(5); 
+0

原始sql查詢是怎樣的?嘗試使用['DB :: raw()'](https://github.com/laravel/laravel/blob/master/laravel/database.php#L123)。 – Michelle 2013-03-01 13:43:17

+0

在select()中使用DB :: raw()工作,謝謝。 – Lee 2013-03-01 19:23:59

+0

它實際上會理解爲很好。問題在於減法運算符' - '。正如你所做的那樣使用DB :: raw()是處理這種情況的正確方法。 – 2013-03-13 03:05:45

回答

1

試試這個:

Quote::where('created_at', '>=', $date) 
     ->select(array('id',DB::raw('(downvotes - upvotes) as votes'))) //and what you need 
     ->where('created_at', '<=', date('Y-m-d').' 23:59:59') 
     ->order_by('upvotes', 'desc') 
     ->order_by('votes', 'desc') 
     ->paginate(5); 
+0

不工作,'(downvotes - upvotes)票作爲'SELECT id','(downvotes'AS'upvotes)','quotes',',因此拋出一個錯誤。 – Lee 2013-03-01 19:03:29

+0

可能使用DB:raw是必需的。你可以再試一次嗎? – Bilal 2013-03-01 20:51:29

+0

對不起,我沒有看到你解決這個問題。 – Bilal 2013-03-01 20:53:14

0

$selectdata = DB::table('TableDetails') ->leftJoin('TableStatus', 'TableDetails.TableID', '=', 'TableStatus.TableID') ->leftJoin('LoginUser', 'TableStatus.WaiterLoginID', '=', 'LoginUser.LoginID') ->leftJoin('UserRole', 'LoginUser.UserRoleID', '=', 'UserRole.UserRoleID') ->select('LoginUser.UserName','UserRole.UserRoleName','TableStatus.TableStatus','TableStatus.TableTimeStatus','TableStatus.WaiterLoginID','TableDetails.TableSeatCount - TableStatus.TableSeatOccupied AS TableRemainingCount') ->get();

之前,它的工作對我來說減號之後就過着 '空間'。