fix: speed up paste random function a lot

This commit is contained in:
Floorb 2023-05-20 10:06:26 -04:00
parent 83f4fa56c4
commit 0b6f54b0d6

View file

@ -104,12 +104,31 @@ class Paste extends Model {
->limit($count)->get(); ->limit($count)->get();
} }
public static function getRandom(int $count = 10) : Collection { public static function getRandom(int $count = 10) : array {
return Paste::with('user') $total_pastes = Paste::count();
->where('visible', self::VISIBILITY_PUBLIC) $pastes = [];
->where('is_hidden', false)
->whereRaw("((expiry IS NULL) OR ((expiry != 'SELF') AND (expiry > NOW())))") for ($i = 0; $i < $count; $i++) {
->orderByRaw('RAND()') $pastes[] = self::getSingleRandom($total_pastes);
->limit($count)->get(); }
return $pastes;
}
private static function getSingleRandom(int $total) {
$paste = null;
do {
$paste_id = rand(1, $total);
$paste = Paste::with('user')
->where('visible', self::VISIBILITY_PUBLIC)
->where('is_hidden', false)
->whereRaw("((expiry IS NULL) OR ((expiry != 'SELF') AND (expiry > NOW())))")
->where('id', $paste_id)
->first();
} while (!$paste);
return $paste;
} }
} }