Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Sorting a has_many relationship


Go to End


4 Posts   4366 Views

Avatar
dendeffe

Community Member, 135 Posts

14 February 2010 at 2:47am

Hi, I have to DataObjects: Continent and Region.

class Continent extends DataObject {
	static $db = array(
		'Title' => 'Varchar(255)',
	);
	
	static $has_many = array(
		'Regions' => 'Region'
	);
}

and

class Region extends DataObject {
	static $db = array(
		'Title' => 'Varchar(255)',
	);
	
	static $has_one = array(
		"Continent" => "Continent"
	);
}

I get them from the DB

	function Continents() {
		return DataObject::get("Continent", "", "Continent.Title ASC");
	}

And use them in the template

<% control Continents %>
<h3>$Title</h3>
	<% control Regions %>
	<p>$Title</p>
	<% end_control %>
<% end_control %>

How can I make sure that the Regions are listed in alphabetical order?

Avatar
Willr

Forum Moderator, 5523 Posts

14 February 2010 at 2:54pm

You can do this a couple of ways..

1) Define the $default_sort on Region. If you always want regions in alphabetical order then this is probably the easier solution. SS will automatically sort any dataobject get call by the $default_sort field (by default ID asc)

class Region extends DataObject {
...
static $default_sort = 'Title ASC';
..

2) The other way (if you don't want to affect the sorting over all regions) is to make a function on Continent which returns a sorted list of regions.

class Continent extends DataObject {
...
function getAlphabeticalOrderedRegions() {
$regions = $this->Regions();
if($regions) $regions->sort('Title');

return $regions;
}

Then you can use <% control AlphabeticalOrderedRegions %> in your template.

Avatar
dendeffe

Community Member, 135 Posts

14 February 2010 at 8:11pm

Thanks Willr, that works great.

Avatar
dhensby

Community Member, 253 Posts

15 February 2010 at 4:03am

Another solution is this:

function getAlphabeticalOrderedRegions() {
return $this->Regions(null,'Title ASC')
}

I think this is a bit more efficient than using the sort() function as it sorts it during the DB call, rather than using php to do it