dongzhiyi2006
2014-05-04 13:40
浏览 144
已采纳

如何使用Laravel 4的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();
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongliao6777 2014-05-04 13:47
    已采纳

    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

    点赞 打赏 评论
  • donglu5047 2015-10-20 10:37
    $data = Model::where('id',$id)->get()->random($count);
    

    You can use random. It simple and effective.

    点赞 打赏 评论
  • dongshou6041 2016-05-06 08:50

    Just use ->orderBy(DB::raw('RAND()')) in your query

    $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();

    点赞 打赏 评论

相关推荐 更多相似问题