📜 ⬆️ ⬇️

Doctrine and sorting for many-to-one communication

For a long time I have been using a bunch of Zend Framework and Doctrine and there was a lack of sorting for the collections obtained by the link. It turned out that it is easy to implement.

Later in one of the projects created by the company in which I work, a similar method was found, but, alas, it was not clear whether it was leaked from the Doctrine developers or was created in the depths of my team. Confused by the fact that the code snippet found was written for a DBMS that is not used in our company.

All manipulations were made on version 1.1.3, but should bear fruit when using earlier versions of Doctrine.
')
The method is to edit a single file. Yes, making modifications to the code of a third-party library is not good, but, unfortunately, at the moment there is no other way out. Or was I looking bad?

Open the Doctrine / Relation.php file and find the place to describe the array of definitions:

protected $ definition = array (...);

Add another key / value pair:

'order' => null,

This is necessary due to the fact that Doctrine, on the basis of this array, makes a list of definitions passed to its classes specified during the formation of links.

We find the definition of the getRelationDql function and add the code to implement sorting. Thus, the function will be as follows:

 public function getRelationDql ($ count)
 {
     $ component = $ this-> getTable () -> getComponentName ();

     $ dql = 'FROM'.  $ component
           .  'WHERE'.  $ component.  '.'  .  $ this-> definition ['foreign']
           .  'IN ('. Substr (str_repeat ('?,', $ count), 0, -2). ')';

     if (! empty ($ this-> definition ['order']))
     {
         $ dql. = 'ORDER BY'.  $ this-> definition ['order'];
     }

     return $ dql;
 }

Those. we indicate the need for sorting in case it is defined in the link description. It is in this code fragment that ORDER BY can take other forms for different SQL dialects.

It remains to define the relationship to specify the sort:

$ this-> hasMany ('Products', array ('local' => 'id', 'foreign' => 'category_id', 'order' => 'position desc'));

Thus, the collections are sorted for the connection of many to one, which was what was required to receive. I hope that the article will be useful to someone.

Source: https://habr.com/ru/post/68806/


All Articles