PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 30, 2021

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

 December 30, 2021     cakephp, cakephp-3.0     No comments   

Issue

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

Solution

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;


Answered By - arilia
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing