我有一个名为 Question
的 Eloquent 模型链接到名为 questions
的数据库表。
是否有 Eloquent 函数可以让我从数据库中提取一个随机问题(或一组随机问题)?类似于以下内容:
$random_question = Question::takeRandom(1)->get();
或
$random_questions = Question::takeRandom(5)->get();
最佳答案
只需要做:
$random_question = Question::orderBy(DB::raw('RAND()'))->take(1)->get();
和
$random_question = Question::orderBy(DB::raw('RAND()'))->take(5)->get();
如果您想使用您在问题中指定的语法,您可以使用范围。
在模型 Question
中,您可以添加以下方法:
public function scopeTakeRandom($query, $size=1)
{
return $query->orderBy(DB::raw('RAND()'))->take($size);
}
现在您可以执行 $random_question = Question::takeRandom(1)->get();
并获得 1 个随机问题。
您可以在 http://laravel.com/docs/eloquent#query-scopes 阅读有关 Laravel 4 查询范围的更多信息
关于php - 如何使用 Laravel 4 的 Eloquent ORM 从数据库中选择随机条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23456947/