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();
$pastes = [];
for ($i = 0; $i < $count; $i++) {
$pastes[] = self::getSingleRandom($total_pastes);
}
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('visible', self::VISIBILITY_PUBLIC)
->where('is_hidden', false) ->where('is_hidden', false)
->whereRaw("((expiry IS NULL) OR ((expiry != 'SELF') AND (expiry > NOW())))") ->whereRaw("((expiry IS NULL) OR ((expiry != 'SELF') AND (expiry > NOW())))")
->orderByRaw('RAND()') ->where('id', $paste_id)
->limit($count)->get(); ->first();
} while (!$paste);
return $paste;
} }
} }