im_tsm
im_tsm

Reputation: 2051

Laravel 5: order by subtraction in eloquent relationship

How to perform this query using Eloquent

select * from `reviews` order by `up_vote` - `down_vote` desc

I am trying to do something like this:

$top_reviews = $productDetails->reviews()->orderBy('up_vote - down_vote','DESC')->get();

But I am getting Unknown column 'up_vote - down_vote'. Is it possible to do this without using DB ? Update: I have found a method orderByRaw which working fine. See Laravel API docs. Now I am doing like this:

$productDetails->reviews()->orderByRaw('`up_vote` - `down_vote` DESC')->get();

Upvotes: 0

Views: 1787

Answers (2)

Yurich
Yurich

Reputation: 577

I think, You should do

$reviews->select('*', '(up_vote - down_vote) AS profit')
    ->orderBy('profit','DESC')->get();

Upvotes: 2

Drudge Rajen
Drudge Rajen

Reputation: 7987

Something like this :

$top_reviews = $reviews()->orderBy('up_vote', '-', 'down_vote','DESC')->get();

Upvotes: 0

Related Questions