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 defined in relational instantiation.

Hey guys i am wondering if i have my syntax wrong here? or if it is not part of the spec?

This doesn't work. I get the response back in ascending ID, instead of DESC noteDate.

$this->hasMany('id','Nova\Models\Notes','accountId', array(
    'alias' => 'notes',
    'order' => 'noteDate DESC'
));

I can directly manipulate it after the fact by doing the following.

$account->notes = $account->getNotes(array('order' => 'noteDate DESC'));

but i hate having to reset teh value its just more overhead. its not detrimental right now. but its just one more thing i don't want to have to do. every time i summon up an object.



17.5k

I've also found that in order to have the relations returned in the fetch I have to specifically set it as such. You can put it in the afterFetch method though and you won't have to specify every time.

    public function initialize() {
        $this->hasMany('id','Nova\Models\Notes','accountId', array(
            'alias' => 'notes',
            'order' => 'noteDate DESC'
        ));
    }

    public function afterFetch() {
        $this->notes = $this->notes; //'notes' is the alias as specified above.
    }

That's neat you can specify the order though... I didn't know you could do that.



145.0k
Accepted
answer

To use order in relations you need to do this like this:

$this->hasMany('id','Nova\Models\Notes','accountId', array(
            'alias' => 'notes',
            'params' => [
                'order' => 'noteDate DESC'
            ]
        ));

the magic getters work just like any other finder, i am pretty sure you can add anythign you need as a query param

I've also found that in order to have the relations returned in the fetch I have to specifically set it as such. You can put it in the afterFetch method though and you won't have to specify every time.

  public function initialize() {
      $this->hasMany('id','Nova\Models\Notes','accountId', array(
          'alias' => 'notes',
          'order' => 'noteDate DESC'
      ));
  }

  public function afterFetch() {
      $this->notes = $this->notes; //'notes' is the alias as specified above.
  }

That's neat you can specify the order though... I didn't know you could do that.

A herp derp. . . i have this exact syntax in other places i was just totall blind....

To use order in relations you need to do this like this:

$this->hasMany('id','Nova\Models\Notes','accountId', array(
           'alias' => 'notes',
           'params' => [
               'order' => 'noteDate DESC'
           ]
       ));