sort has_many by has_one relation in silverstripe
Asked Answered
T

2

6

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?

Trews answered 12/11, 2013 at 16:59 Comment(0)
N
7

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'));
}
Nathalia answered 13/11, 2013 at 9:52 Comment(0)
N
1

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

Neptunium answered 26/1, 2016 at 16:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.