Adam
Adam

Reputation: 355

Laravel 4: Order query relation randomly and limited

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

Answers (2)

hayhorse
hayhorse

Reputation: 2652

$products = Category::find($id)->products()->orderBy(DB::raw('RAND()'))->take($limit)->get();

(sorry forgot the ->get() in my original answer)

Upvotes: 9

Yada
Yada

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

Related Questions