How to get SQL statements to randomly fetch 10 data in Laravel

Source: Internet
Author: User
Keywords Php laravel

Reply content:

First, attach the MySQL official documentation excerpt and Link:

ORDER BY RAND()Combined with are LIMIT useful for selecting a random sample from a set of rows:

Simple translation of the above (for students who are not good at English):

ORDER BY RAND()And LIMIT used together, can be used to select a random part from multiple rows of results

mysql> SELECT * FROM table1, table2 WHERE a=b AND c
  
   < code="">

其次,使用Laravel Eloquent的查询器(query builder),需要用到DB(Facade)进行原生查询:

因为不了解你的查询的上下文,所以这里用假想的Post模型进行说明

$post = Post::where('category_id', $category_id) ->orderBy(\DB::raw('RAND()')) ->take(10) ->get();

解释:

    1. Eloquent的orderBy方法只支持第二个参数为ASCDESC,因此,这里需要调用DB::raw方法来实现原生查询

    2. 另外,还可以使用orderByRaw('RAND()'),效果等同

    3. 限制结果数目,要用Eloquent的take方法,相当与SQL的LIMIT

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.