Laravel 4:随机且有限的顺序查询关系
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20132051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4: Order query relation randomly and limited
提问by Adam
I'm using Laravel 4 and I'm running into an issue with eloquent.
我正在使用 Laravel 4,但遇到了 eloquent 的问题。
I've got it set up to grab the category, get the products and limit it to 2. However I'm having trouble getting the random element. I need it to select from two random products, rather than the newest/latest.
我已将其设置为获取类别、获取产品并将其限制为 2。但是我无法获取随机元素。我需要它从两个随机产品中进行选择,而不是最新的/最新的。
$products = Category::find($id)->products->take($limit);
$products->load('imageThumb');
return $products;
I'd like to keep the solution eloquent based, but if that's not an option I'll switch to a raw query code.
我想保持解决方案雄辩的基础,但如果这不是一个选项,我将切换到原始查询代码。
Thanks!
谢谢!
回答by hayhorse
$products = Category::find($id)->products()->orderBy(DB::raw('RAND()'))->take($limit)->get();
(sorry forgot the ->get() in my original answer)
(抱歉忘记了我原来的答案中的 ->get())
回答by Yada
How's big is the table? If it is not too big you can use MySQL ORDER BY RAND() http://davidwalsh.name/mysql-random
桌子有多大?如果它不是太大,您可以使用 MySQL ORDER BY RAND() http://davidwalsh.name/mysql-random
Eloquent something like:
雄辩的东西,如:
->orderBy(DB::raw('RAND()'))