Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort has_many by has_one relation in silverstripe

Tags:

silverstripe

I've got three DataObjects in Silverstripe 3.1: an Issue, a Vote, and a Voter. Issues have many Votes; Votes have one Voter and one Issue. On my Issue_show page, I want to show all that Issue's Votes, sorted by Voter's Name.

The function in the Issue looks like this:

public function MyVotes() {
     return $this->Votes();
}

But I can't figure out how to access the Voter's Name to sort by it. Presumably, it should be something like

public function MyVotes() {
    return $this->Votes()->sort('Voter.Name');
} 

but that throws an error. What step am I missing?

like image 465
mierla Avatar asked Nov 12 '13 16:11

mierla


2 Answers

For a has_one relation you need to add the ID suffix to the fieldname. Also, relation casting in DataList->sort() unfortunately does only work with an array.

public function MyVotes() {
return $this->Votes()->sort(array('VoterID.Name'=>'ASC'));
}
like image 138
Devlin Avatar answered Sep 25 '22 08:09

Devlin


You could also handle sorting in the template something like this:

<% loop Votes.Sort('VoterID.Name') %>
    ...

This hasn't been tested but pretty sure that should work

like image 28
Peter Harley Broom Avatar answered Sep 23 '22 08:09

Peter Harley Broom