0

In Laravel 5 framework: How can I select a random row using Eloquent Postgres SQL?

i want get random 3 recomment product.

i find code:

$recomment_product = Product::whereRaw("name = '".$product->name."' and gender = '".$product->gender."' and client_target = '".$product->client_target."'")->orderByRaw(DB::raw("RAND()"))->take(3)->get();

But it not work. Please Help!

Hưng Trịnh
  • 947
  • 1
  • 12
  • 23

1 Answers1

3

Eloquent has inRandomOrder() method.

$recomment_product = Product::where('name', $product->name)
    ->where('gender', $product->gender)
    ->where('client_target', $product->client_target)
    ->inRandomOrder()
    ->take(3)
    ->get();
IndianCoding
  • 2,602
  • 1
  • 6
  • 12