Reputation: 355
I'm using Laravel 4 and I'm running into an issue with 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.
$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!
Upvotes: 2
Views: 9052
Reputation: 2652
$products = Category::find($id)->products()->orderBy(DB::raw('RAND()'))->take($limit)->get();
(sorry forgot the ->get() in my original answer)
Upvotes: 9
Reputation: 31225
How's big is the table? If it is not too big you can use MySQL ORDER BY RAND() http://davidwalsh.name/mysql-random
Eloquent something like:
->orderBy(DB::raw('RAND()'))
Upvotes: 0