Last active
May 12, 2016 21:06
-
-
Save vluzrmos/8046e20769a595a4b0d0 to your computer and use it in GitHub Desktop.
Laravel Eloquent Agnostic Random Statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait HasRandomStatementTrait | |
{ | |
/** | |
* Random Statements by driver name. | |
* @var array | |
*/ | |
protected $randomStatements = [ | |
'mysql' => 'RAND()', | |
'pgsql' => 'RANDOM()', | |
'sqlite' => 'RANDOM()', | |
'sqlsrv' => 'NEWID()', | |
]; | |
/** | |
* Default random statement. | |
* | |
* @var string | |
*/ | |
protected $defaultRandomStatement = 'RANDOM()'; | |
/** | |
* Scope to order by random statement. | |
* | |
* @param \Illuminate\Database\Query\Builder $query | |
* @param string $driver | |
* @return \Illuminate\Database\Query\Builder | |
*/ | |
public function scopeOrderByRandom($query, $driver = null) | |
{ | |
return $query->orderByRaw($this->getRandomStatement($driver)); | |
} | |
/** | |
* Get random statement for a given driver name. | |
* | |
* @param string $driver | |
* @return string | |
*/ | |
public function getRandomStatement($driver = null) | |
{ | |
$driver = $driver ?: $this->getCurrentDriverName(); | |
if (isset($this->randomStatements[$driver])) { | |
return $this->randomStatements[$driver]; | |
} | |
return $this->defaultRandomStatement; | |
} | |
/** | |
* Get the driver name for the current connection. | |
* | |
* @return string | |
*/ | |
public function getCurrentDriverName() | |
{ | |
return $this->getConnection()->getDriverName(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment