Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent AS keyword

I'm trying to use the keyword AS to combine two columns so I can sort on that column.

This is the full query as it at the moment.

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

I would like to do

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

Thank you.


Solution

Seems as though using DB::raw() is the only way to do it, Laravel/Eloquent just doesn't understand the AS.

Working solution is

 $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);
like image 287
Lee Avatar asked Jan 27 '26 11:01

Lee


1 Answers

Try this:

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);
like image 111
Bilal Gultekin Avatar answered Jan 30 '26 11:01

Bilal Gultekin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!