Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3 : How to get max amout row from a table

I have table call users , like

id name amount   created
1   a   100     6-16-2016
2   b   200     5-16-2016

I need max amount full row, I have tried below code but getting syntax error.

  $user = $this->Users->find('all',[
         'fields' => array('MAX(Users.amount)  AS amount'),
  ]); 
like image 288
Satu Sultana Avatar asked Jun 16 '16 04:06

Satu Sultana


2 Answers

simplest way

$user = $this->Users->find('all',[
   'fields' => array('amount' => 'MAX(Users.id)'),
]); 

using select instead of an options array

$user = $this->Users->find()
    ->select(['amount' => 'MAX(Users.id)']); 

making use of cake SQL functions

$query = $this->Users->find();
$user = $query
    ->select(['amount' => $query->func()->max('Users.id')]);

the above three all give the same results

if you want to have a single record you have to call ->first() on the query object:

$user = $user->first();
$amount = $user->amount;
like image 118
arilia Avatar answered Jan 27 '23 11:01

arilia


Simplest method using CakePHP 3:

$this->Model->find('all')->select('amount')->hydrate(false)->max('amount')

Will result in an array containing the maximum amount in that table column.

like image 30
MotsManish Avatar answered Jan 27 '23 11:01

MotsManish