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'
    )
));


81.3k

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

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


16.5k

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]) %}


16.5k

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 :

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