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

故事扮演 提交于 2019-12-07 09:56:42

问题


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'),
  ]); 

回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/37850117/cakephp-3-how-to-get-max-amout-row-from-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!