Jump to:

23375 Posts in 18175 Topics by 2866 members

General Questions

SilverStripe Forums » General Questions » Sorting a has_many relationship

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

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

Page: 1
Go to End
Author Topic: 2223 Views
  • dendeffe
    Avatar
    Community Member
    135 Posts

    Sorting a has_many relationship Link to this post

    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?

  • Willr
    Avatar
    Forum Moderator
    5489 Posts

    Re: Sorting a has_many relationship Link to this post

    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.

  • dendeffe
    Avatar
    Community Member
    135 Posts

    Re: Sorting a has_many relationship Link to this post

    Thanks Willr, that works great.

  • Pigeon
    Avatar
    Community Member
    243 Posts

    Re: Sorting a has_many relationship Link to this post

    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

    2223 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.