nilesh
nilesh

Reputation: 99

How to select particular columns with ORDER BY clause in zend framework2

I'm new to zend framework and i know this is a beginner level question.But i'm totally messed up.

I want to retrieve only user_id and user_name form database with descending order of user_id.

I'm using tablegateway.

I'm calling getUsersTable() function as

$result = $this->getUsersTable()->select();

and getUsersTable() function is

 public function getUsersTable()
    {
     if(!$this->usersTable)
     {

      $this->usersTable = new TableGateway('eo_user',$this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
      );
     }   
     return $this->usersTable;

    }

I searched for similar problem but solution was not looking related to tablegateway.

What changes should i do?Please help.

Upvotes: 1

Views: 2008

Answers (1)

Kunal Dethe
Kunal Dethe

Reputation: 1274

Just so if getUsersTable() function is written in your Controller in the way it is mentioned in the question, you could try this -

  1. add this use statement at the top of the Controller -

    use Zend\Db\Sql\Select;

  2. write this in your action -

    $select = new Select('eo_user'); $select->columns(array('user_id', 'user_name')); $select->order('user_id DESC');

    $result = $this->getUsersTable()->selectWith($select);

Note: If your getUsersTable() is actually returning the TableGateway object then the above code will work fine.

If you have created Model-Table class file like in the 'Album' tutorial then just change the line

$result = $this->getUsersTable()->selectWith($select); 

to

$result = $this->tablegateway->selectWith($select);
//This is to be written in that Table Class file.

I hope it helps someone.

Upvotes: 1

Related Questions