We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Ordering related models

There doesn't appear to be any way to efficiently order a related model that is part of a one-to-many relationship.

Using the following code as my example set:

Model Posts (has many comments) Model Comments (belongs to posts)

$posts = Posts::find();

I understand the current options for ordering related models are:

  • getRelated()
  • getComments() (which will wrap getRelated() anyway)

Could related model ordering be passed as an array? Perhaps like this:

$posts = Posts::find(array(
    'order' => 'date desc',
    'comments' => array(
        'order' => 'date desc'
    )
));


98.9k

You can pass the order clause to the method that obtain the related records:

$posts->getComments(['order' => 'date desc']);


31.3k

Hi,

regarding this post, I'd like to point out that this code doesn't work and about me, it shouls be :

{% set orderBy = 'Number ' ~ c.Order %}

{% set companyRouteNumber = c.getCompanyRouteNumber(['order' => orderBy]) %}

This failed with the Volt compiler. Is there a way to pass the order column with the direction programmaticaly ?

Thank you !

Hi,

i dont know what problem exactly do you have, but in the Volt is array defined like this ['order': 'number asc'].

instead => use :

So in your case like this :

{% set orderBy = 'Number ' ~ c.Order %}
{% set companyRouteNumber = c.getCompanyRouteNumber(['order' : orderBy]) %}


31.3k

Hi,

Yes I realise that, but I forgot to come back to mention.

Thank you.

Hi,

i dont know what problem exactly do you have, but in the Volt is array defined like this ['order': 'number asc'].

instead => use :

So in your case like this :

{% set orderBy = 'Number ' ~ c.Order %}
{% set companyRouteNumber = c.getCompanyRouteNumber(['order' : orderBy]) %}

Hello colleagues!

Is it possible to add order in relations in model, like so:

    $this->hasMany(
        "id",
        InvoicesRows::class,
        "lasku_id",
        [
            "alias" => "rows",
            "order" => "id DESC"
        ]
    );


43.9k

Hi,

I think that this is not possible. But just give it a try and tell us ;-)

Try this:

$this->hasMany(
    'id',
    InvoicesRows::class,
    'lasku_id',
    [
        'alias'    => 'rows',
        'reusable' => true,
        'params'   => [
            'order' => 'id DESC',
        ],
    ]
);