Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Yii2 Random Model (ActiveRecord)
<?php
// Todo: Place this snippet into your Model class.
/**
* Get random model(s) from table
* @see \yii\db\ActiveQuey
* @param array|string|null (optional) $columns Columns to be fetched (default: all columns)
* @param array $options Additional options pass to function<br>
* <code>
* (array) condition Where Condition
* (int) limit Number of models (default: 1)
* (bool) asArray Return model attributes as [key=>value] array
* (callable) callback Apply a callback on ActiveQuery
* function ( \yii\db\ActiveQuery $query ){
* // some logic here ...
* }
* </code>
* @return array|null|\yii\db\ActiveRecord|\yii\db\ActiveRecord[]
*/
public static function getRandom ( $columns = null, array $options = [] ) {
$condition = $options['condition'] ?? [];
$asArray = $options['asArray'] ?? false;
$callback = $options['callback'] ?? null;
$limit = $options['limit'] ?? 1;
$query = static::find()
->select($columns)
->where($condition)
->orderBy(new \yii\db\Expression('rand()'))
->limit((int)$limit);
if ( $asArray ) {
$query->asArray(true);
}
if ( is_callable($callback) ) {
call_user_func_array($callback, [&$query]);
}
return $limit === 1
? $query->one()
: $query->all();
}
//**** Example
/*
$model = Model::getRandom(null, [
'asArray'=>true
]);
\yii\helpers\VarDumper::dump($mode, 10, true);
*/
@gvanto

This comment has been minimized.

Copy link

@gvanto gvanto commented Dec 3, 2018

Nice, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment