简体   繁体   中英

How can I select a random entry from a database using Laravel 4's Eloquent ORM?

I have an Eloquent model called Question linked to a database table named 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:

$random_question = Question::takeRandom(1)->get();

or

$random_questions = Question::takeRandom(5)->get();

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:

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.

You can read more about Laravel 4 query scopes at http://laravel.com/docs/eloquent#query-scopes

$data = Model::where('id',$id)->get()->random($count);

You can use random. It simple and effective.

只需在查询中使用 - > 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM