2013-03-01 56 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();

之前,它的工作对我来说减号之后就过着 '空间'。