1

please help me, i have query: SELECT * from (select * from products ORDER BY id DESC LIMIT 20) AS result ORDER BY discount DESC LIMIT 14

so, how to convert into query builder in laravel 5. tks!

2
  • have a look on this, might help. Commented Jun 17, 2017 at 19:48
  • tks guy, i did it Commented Jun 18, 2017 at 3:35

2 Answers 2

2

Using the query builder and importing (use) DB, allows you to build and fetch the result you want.

use DB;

$result = DB::table(
    DB::raw("(" . 
        DB::table('products')
          ->select('*')
          ->orderBy('id', 'desc')
          ->limit(20)
          ->toSql()
        . ") as result"
    )
)
->select('*')
->orderBy('discount', 'desc')
->limit(14)
->get();

table() selects the table you want to query. In this case we are building up a separate SQL statement to fetch the table.

select() the columns you would like to see.

orderBy($column, $direction) where $column is the name of the column you would like to order and $direction is the order, desc or asc.

limit($limit) only return $limit items to the result set.

toSql() returns the current QueryBuilder SQL statement as a string.

get() returns the data in a Collection.

Also added in the missing discount ordering.

Sign up to request clarification or add additional context in comments.

2 Comments

please add some context to your answer. just code alone usually doesn't make for good answers
I think you've missed the "ORDER BY discount DESC"
0

Try something like:

Products::orderBy('id', 'desc')->take(20)->orderBy('discount', 'desc')->take(14)->get();

2 Comments

tks guy, i tried it, but result not orderBy('discount'). it given 14 record orderby('id', 'desc'). Do you have any other making?
You can use: $q = Products::orderBy('id', 'desc')->take(20)->get(); And after that $test = $q->sortByDesc('nome')->take(14); See if this works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.