21278 Posts in 5728 Topics by 2599 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 1609 Views |
-
Sorting a has_many relationship

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?
-
Re: Sorting a has_many relationship

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.
-
Re: Sorting a has_many relationship

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
| 1609 Views | ||
|
Page:
1
|
Go to Top |



