Laravel - randomly select n number of rows containing same value in certain column after applying 'order by'

▼魔方 西西 提交于 2020-02-06 09:27:13

问题


In my Laravel project, in the database table ads, I have the following structure :

id | col1 | col2

col2 has values like topad, bump,urgent along with empty value. I want to take all the rows from the ads table and sort them alphabetically based on col2 in descending order.

So I used:

Ads::orderBy('col2','DESC')->get()

Now I have 2 conditions to be applied on the query.

1st condition : Suppose there are 4 rows with topad in col2, 5 rows with urgent in col2, 6 rows with bump in col2 and 7 rows each with an empty value in col2 . So rows with urgent in col2 will appear 1st, with topad in col2 will appear 2nd and with bump in col2 will appear 3rd and with empty values in col2 will appear 4th. Now I need to randomize the rows' order within each set. For example , rows with topad in col2 may have the ids 1,2,3,4. I want to randomize these rows (which may result into for example 4,2,1,3). But they will appear before rows containing topad in col2. Same is true for topad and bump row sets and rows containing any empty value in col2.

So the query becomes :

Ads::orderBy('col2','DESC')->inRandomOrder()->get(); 

2nd condition : Suppose rows are ordered by col2 values. But from each set of rows containing same value in col2, I need n number of rows from those that have non-empty value in col2 i.e. randomly I need n rows from urgented rows, n from topaded rows, n from bumped rows and all from emptyed rows.

How to write the query then ?


回答1:


You could do this with subqueries, but in my experience they take more time to execute then a few smaller ones (if they are indexed correctly). Also, you have more control over the limits and debugging issues.

$top_ads = Ads::whereCol2('topad')->inRandomOrder()->limit(5)->get();
$urgent_ads = Ads::whereCol2('urgent')->inRandomOrder()->limit(10)->get();
$bump_ads = Ads::whereCol2('bump')->inRandomOrder()->limit(2)->get();

This will create your queries and after that you can do whatever you want with their collections. Combine them, reorder them, etc.



来源:https://stackoverflow.com/questions/59956706/laravel-randomly-select-n-number-of-rows-containing-same-value-in-certain-colu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!