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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With