问题
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 urgent
ed rows, n
from topad
ed rows, n
from bump
ed rows and all from empty
ed 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