Home  >  Article  >  Backend Development  >  laravel 中 如何让sql语句随机取出10条数据

laravel 中 如何让sql语句随机取出10条数据

WBOY
WBOYOriginal
2016-06-06 20:10:372820browse

laravel 中 如何让sql语句随机取出10条数据

回复内容:

laravel 中 如何让sql语句随机取出10条数据

首先,附上MySQL官方文档摘录及链接:

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

就上述进行简单翻译如下(对英文不好的同学):

ORDER BY RAND()LIMIT一起使用,可以用于从多行结果中选取随机的一部分

<code>mysql> SELECT * FROM table1, table2 WHERE a=b AND c<d order by rand limit></d></code>

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

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

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

解释:

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

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

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn