Laravel - Randomly Select N Number Of Rows Containing Same Value In Certain Column After Applying 'order By'
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
Solution 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.
Post a Comment for "Laravel - Randomly Select N Number Of Rows Containing Same Value In Certain Column After Applying 'order By'"