mierla
mierla

Reputation: 63

sort has_many by has_one relation in 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?

Upvotes: 6

Views: 1076

Answers (2)

Peter Harley Broom
Peter Harley Broom

Reputation: 115

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

Upvotes: 1

Devlin
Devlin

Reputation: 86

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

Upvotes: 7

Related Questions