Search code examples
zend-frameworkzend-dbzend-framework3

syntax for selecting the last recordset in my model


I tried different possibilities but nothing worked, in the tutorial I couldn't find an example either.

I have a method in my modelclass:

    public function getlastImport($filename)
{
    //$id = (int) $id;
    $rowset = $this->tableGateway->select(['Path' => $filename]);
    $row = $rowset->current();
    if (! $row) {
        throw new RuntimeException(sprintf(
                'Could not find row with identifier %d',
                $id
                ));
    }

    return $row;
}

I want to retrieve the last import of a given filename, so ist must be like in sql:

select max(ID) from table where filename = $filename;

But how would be the right syntax in this case?


Solution

  • The sql query should be

    "SELECT * FROM table_name WHERE filename={$filename} ORDER BY id DESC LIMIT 1" 
    

    Use as the following in your model

    public function getlastImport($filename)
    {
    
        $select = $this->tableGateway->getSql()->select();
        $select->columns(array('id', 'filename', 'label'));
        $select->where(array('filename' => $filename));
        $select->order("id DESC");
        $select->limit(1);
    
        $result = $this->tableGateway->selectWith($select);
        $row = $result->current();
    
        if (! $row) {
            throw new RuntimeException(sprintf(
                'Could not find row with identifier %d',
                $id
            ));
        }
    
        return $row;
    }
    

    Hope this would help you!