Add limit to random result

This commit is contained in:
Dennis Eichhorn 2016-08-08 15:44:08 +02:00
parent 2b2808ef4e
commit 0351533b05
6 changed files with 18 additions and 9 deletions

View File

@ -994,21 +994,26 @@ class DataMapperAbstract implements DataMapperInterface
/**
* Get random object
*
* @param int $amount Amount of random models
* @param int $relations Relations type
*
* @return array
* @return mixed
*
* @since 1.0.0
* @author Dennis Eichhorn <d.eichhorn@oms.com>
*/
public static function getRandom(int $relations = RelationType::ALL)
public static function getRandom(int $amount = 1, int $relations = RelationType::ALL)
{
$query = new Builder(self::$db);
$query->prefix(self::$db->getPrefix())
->random(static::$primaryKey)
->from(static::$table);
->from(static::$table)
->limit($amount);
return self::get(self::$db->con->prepare($query->toSql())->execute(), $relations);
$sth = self::$db->con->prepare($query->toSql());
$sth->execute();
return self::get($sth->fetchAll(), $relations);
}
/**

View File

@ -48,6 +48,8 @@ class MicrosoftGrammar extends Grammar
$expression = '*';
}
return 'SELECT TOP 1 ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY IDX FETCH FIRST 1 ROWS ONLY';
$query->limit = $query->limit ?? 1;
return 'SELECT TOP 1 ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY IDX FETCH FIRST ' . $query->limit . ' ROWS ONLY';
}
}

View File

@ -57,6 +57,6 @@ class MysqlGrammar extends Grammar
$expression = '*';
}
return 'SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY RAND() LIMIT 1';
return 'SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY RAND() ' . $this->compileLimit($query, $query->limit);
}
}

View File

@ -48,6 +48,8 @@ class OracleGrammar extends Grammar
$expression = '*';
}
return 'SELECT ' . $expression . ' FROM (SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY dbms_random.value) WHERE rownum = 1';
$query->limit = $query->limit ?? 1;
return 'SELECT ' . $expression . ' FROM (SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY dbms_random.value) WHERE rownum >= 1 AND rownum <= ' . $query->limit;
}
}

View File

@ -48,6 +48,6 @@ class PostgresGrammar extends Grammar
$expression = '*';
}
return 'SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY RANDOM() LIMIT 1';
return 'SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY RANDOM() ' . $this->compileLimit($query, $query->limit);
}
}

View File

@ -57,6 +57,6 @@ class SqliteGrammar extends Grammar
$expression = '*';
}
return 'SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY RANDOM() LIMIT 1';
return 'SELECT ' . $expression . ' ' . $this->compileFrom($query, $query->from) . ' ORDER BY RANDOM() ' . $this->compileLimit($query, $query->limit);
}
}