簡體   English   中英

如何使用Laravel 4的Eloquent ORM從數據庫中選擇一個隨機條目?

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

我有一個名為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查詢范圍的更多信息。

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

你可以隨機使用。 它簡單有效。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM