【问题标题】:How can I select a random entry from a database using Laravel 4's Eloquent ORM?如何使用 Laravel 4 的 Eloquent ORM 从数据库中选择一个随机条目?
【发布时间】:2014-06-20 20:07:18
【问题描述】:

我有一个名为 Question 的 Eloquent 模型链接到一个名为 questions 的数据库表。

是否有一个 Eloquent 函数可以让我从数据库中提取一个随机问题(或一组随机问题)?类似于以下内容:

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

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

【问题讨论】:

标签: php mysql laravel laravel-4 eloquent


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    $data = Model::where('id',$id)->get()->random($count);
    

    你可以随机使用。简单有效。

    【讨论】:

    • 这种方法适用于少数结果,但如果您有数千个结果,此方法会很慢,因为它首先获取所有结果,然后随机选择一个。
    【解决方案3】:

    你可以这样做:

    $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 查询范围的更多信息

    【讨论】:

    • 两方面都完美。谢谢。
    • @SUB0DH 它可以处理数千条记录吗?它不会减慢应用程序的速度吗?
    猜你喜欢
    • 2015-03-23
    • 2012-09-06
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 2020-04-04
    • 2020-11-08
    相关资源
    最近更新 更多