I did some calculate in a view table for products in MYSQL, so I list these id for product reference id.
$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');
And I want to get the product from those reference id.
$products = Product::whereIn('id', $rederenceIds);
The product content is correct, but the order is wrong, how to load product order by reference id, I know I can do it in MySQL by using ORDER BY FIELD(id,' . $fields . ')
, but I want to find out Laravel way, and hope not use ORDER BY FIELD
command because it seems waste to much database efficiency.
Use order by like this: return User::orderBy('name', 'DESC') ->orderBy('surname', 'DESC') ->orderBy('email', 'DESC') ... ->get(); Hope it works!!
To order by multiple columns in Laravel you can make use of the "orderBy()" method and chain it multiple times for all the conditions. This method accepts the "column" as the 1st parameter and the ordering direction (ASC / DESC) as the 2nd parameter.
To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.
Now here If we want to sort a multiple columns in Laravel by using orderBy (). Or Whenever we need to give multiple column in our query then we can use twice time orderBy () and then give them. So we can give multiple columns in laravel by following example :
As of Laravel 6, the orderBy () and orderByDesc () query builder methods support passing a query, instead of just a column name. When you do this, the query is executed as a subquery within the order by statement. Again, let's break this query down.
Laravel LLC. This app includes a User model with a hasOne company relationship. Meaning, the company name exists in the companies table. There's actually two approaches we can use to order these users by their company. The first is using a join: Let's break this query down.
->select ('users.*') So if we want to give a ‘ASC’ or ‘DESC’ order in query then we can following this example : ->select ('users.*') Read Also : How to count number of files in folder and remove all files in folder in laravel example? My name is Shahriar sagor.
You will have to inject some raw sql, but it's not a nightmare:
$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');
$referenceIdsStr = implode(',', $referenceIds);
$products = Product::whereIn('id', $rederenceIds)->orderByRaw(DB::raw("FIELD(product_id, $referenceIdsStr)"))->get()->all();
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