Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast in query builder laravel

I want to cast orderBy in query builder laravel

because my price is varchar type..

so when it's sorting...the result is far from I want...

my script like this

DB::table('test')->where(...)->orderBy('price')->get();

i already try something like this

$query = CAST(price AS DECIMAL(10,2)) DESC;
DB::table('test')->where(...)->orderBy($query)->get();

how can I cast OrderBy query builder so I can sort price desc

like image 470
Neversaysblack Avatar asked Jan 11 '16 02:01

Neversaysblack


People also ask

What is casts in laravel?

Casting a value means changing it to (or ensuring it is already) a particular type. Some types you might be familiar with are Integer or Boolean . Simply put, type casting is a method of changing an entity from one data type to another.


1 Answers

Try it with orderByRaw():

$query = "CAST(price AS DECIMAL(10,2)) DESC";
DB::table('test')->where(...)->orderByRaw($query)->get();
like image 84
Jeff Avatar answered Sep 19 '22 08:09

Jeff