如何使用 Laravel 4 的 Eloquent ORM 从数据库中选择随机条目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23456947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I select a random entry from a database using Laravel 4's Eloquent ORM?
提问by Garry Pettet
I have an Eloquent model called Question
linked to a database table named questions
.
我有一个名为Question
链接到名为questions
.
Is there an Eloquent function that will let me take a single random question (or a set number of random questions) from the database? Something like the following:
是否有 Eloquent 函数可以让我从数据库中提取一个随机问题(或一组随机问题)?类似于以下内容:
$random_question = Question::takeRandom(1)->get();
or
或者
$random_questions = Question::takeRandom(5)->get();
回答by SUB0DH
Simply you can do:
你可以这样做:
$random_question = Question::orderBy(DB::raw('RAND()'))->take(1)->get();
and
和
$random_question = Question::orderBy(DB::raw('RAND()'))->take(5)->get();
If you want to use the syntax as you specified in your question, you can use scopes.
In the model Question
you can add the following method:
如果要使用问题中指定的语法,可以使用范围。在模型中,Question
您可以添加以下方法:
public function scopeTakeRandom($query, $size=1)
{
return $query->orderBy(DB::raw('RAND()'))->take($size);
}
Now you can do $random_question = Question::takeRandom(1)->get();
and get 1 random question.
现在你可以做$random_question = Question::takeRandom(1)->get();
并得到 1 个随机问题。
You can read more about Laravel 4 query scopes at http://laravel.com/docs/eloquent#query-scopes
您可以在http://laravel.com/docs/eloquent#query-scopes 上阅读有关 Laravel 4 查询范围的更多信息
回答by KAS
$data = Model::where('id',$id)->get()->random($count);
You can use random. It simple and effective.
您可以使用随机。它简单而有效。
回答by Chamandeep
Just use ->orderBy(DB::raw('RAND()')) in your query
只需在查询中使用 ->orderBy(DB::raw('RAND()'))
$featurep= DB::table('tbl_products')
->join('tbl_product_images' , 'tbl_products.ID', '=', 'tbl_product_images.Product_ID')
->where(array('tbl_products.is_Active' => 0,'CategoryID' => $result->CategoryID))
->groupBy('ID')
->orderBy(DB::raw('RAND()'))
->take(4)
->get();
$featurep= DB::table('tbl_products')
->join('tbl_product_images' , 'tbl_products.ID', '=', 'tbl_product_images.Product_ID')
->where(array('tbl_products.is_Active' => 0,'CategoryID' => $result->CategoryID))
->groupBy('ID')
->orderBy(DB::raw('RAND()'))
->take(4)
->get();