How can I Select the MAX of a Column using Zend_Db_Table?
You need to use Zend_Db_Expr to use mysql functions:
return $this->fetchAll( $this->select() ->from($this, array(new Zend_Db_Expr('max(id) as maxId'))) ) );
You can run direct sql, using $db->query();
yours would simply be:
$db->query("SELECT MAX(id) AS maxID FROM myTable");
but if you want the object notation, then you'd do something like this:
$db->select()->from("myTable", array(new Zend_Db_Expr("MAX(id) AS maxID")));
For those looking to just select the max id from their id column in Zend Framework 2 (maybe 3 as well), but getting this error...
While processing primary key data, a known key id was not found in the data array
...note that you'll need to alias MAX(id)
as id
.
Example inside a table extended from the TableGateway
class:
$select = $this->sql->select();$select->columns(['id' => new Expression('MAX(id)')]);$maxId = $this->selectWith($select)->current()->id;return (int) $maxId;