Laravel Eloquent sort by date and also save entries by ranked index
P粉002023326
2023-08-30 14:46:23
<p>I'm building a project using Laravel and I have a table with all my products. On this table, products are added daily and I display all products on the page sorted by <code>created_at</code>. This can be easily done using Laravel Eloquent and <code>->orderBy('created_at', 'DESC')</code>. </p>
<p>However, I would like to be able to "pin"/"pin" certain products to a certain location. To do this, I created the <code>rank_index</code> column, which contains the number that the product should have in the returned query collection. </p>
<p>This is my current table:</p>
<pre class="brush:php;toolbar:false;">title rank_index created_at
An awesome product 2023-01-01 10:04:00
Another product 4 2023-01-01 10:00:00
Baby car 2023-01-01 10:05:00
Green carpet 2 2023-01-01 10:08:00
Toy 2023-01-01 10:07:00</pre>
<p>The following table shows the collection I want the query to return: </p>
<pre class="brush:php;toolbar:false;">title rank_index created_at
Toy 2023-01-01 10:07:00
Green carpet 2 2023-01-01 10:08:00
Baby car 2023-01-01 10:05:00
Another product 4 2023-01-01 10:00:00
An awesome product 2023-01-01 10:04:00</pre>
<p>I hope there is a solution to return such a table directly from the database. This way I don't have to split and slice the collection which makes the request much slower! Otherwise, I have to use PHP functions to rearrange, split, and slice the collection. </p>
<p>I'd be happy for any help! </p>
<p>Kind regards</p>
I would almost certainly choose Silver's solution
Your Statement:
makes no sense. Splitting/slicing/stitching the two result sets together is unlikely to have a measurable impact on performance. It certainly won't make "requests slow"!
This is a SQL solution for your scenario, but it will almost certainly be slower than stitching two result sets together, depending on the size of the tables involved.
If you have more than 1000 toys, the recursive cte will reach the default value cte_max_recursion_depth, as explained here.
You can remove the restriction by running the following command before the above query:
Or change the recursive CTE to a non-recursive CTE with "nofollow noreferrer">ROW_NUMBER() on the toys table:
This is a playable dbfiddle.
I have encountered it this year. Sorting directly in the query is more complicated. You can refer to this questionMySQL result set is sorted by fixed positionIf you want to understand its complexity in depth.
What I did before was relatively simple and was completed through two queries,
This is an example you can refer to