Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use Count in where has Condition by laravel eloquent

I have two tables :

customer table =


id,
score,
total_buy,
(this table has many transaction)

And have a transaction table too


customer_id,
value,
score,
created_at,
(this table blongs to a customer)

i want Search on customer where has 5 transaction and one of them created at 2017/1/1 date and where customer score and value more than 200 and take 10 row By Random order (its a lottery system ) i Trying this code before ask

customer::
      whereHas('transactions', function ($query) use ($last_transaction)
      {
        $query->whereDate('created_at',$last_transaction);
      })
      ->where('total_buy', '>=',$r->minvalue)
      ->where('score', '>=',$r->score)
      ->inRandomOrder()
      ->take($r->customernumber)
      ->get();

but i dont know how counting Row subrelation in where has

like image 574
Mahdi Mirhendi Avatar asked Sep 01 '25 21:09

Mahdi Mirhendi


1 Answers

Use havingRaw().

customer::
  whereHas('transactions', function ($query) use ($last_transaction)
  {
    $query->havingRaw('COUNT(*) > 4');
  })->
  whereHas('transactions', function ($query) use ($last_transaction)
  {
    $query->whereDate('created_at',$last_transaction);
  })
  ->where('total_buy', '>=',$r->minvalue)
  ->where('score', '>=',$r->score)
  ->inRandomOrder()
  ->take($r->customernumber)
  ->get();

This will check for atleast 5 transactions. If you need exact 5, then use equal operator.

like image 68
Sohel0415 Avatar answered Sep 03 '25 14:09

Sohel0415