本文介绍了Cakephp 3:如何从表中获取最大行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表呼叫用户,例如

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


推荐答案

最简单的方法

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

使用select而不是选项数组

using select instead of an options array

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

利用Cake SQL函数

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

如果您想拥有一条记录,则必须在查询对象上调用-> first()

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

$user = $user->first();
$amount = $user->amount;

这篇关于Cakephp 3:如何从表中获取最大行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 15:42