Jump to:

3431 Posts in 1058 Topics by 734 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Complex query for getting latest news articles by unique category and sorted by date

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

Page: 1
Go to End
Author Topic: 1112 Views
  • LesC
    Avatar
    Community Member
    70 Posts

    Complex query for getting latest news articles by unique category and sorted by date Link to this post

    Hi folks,

    I'm trying to display 3 latest news articles on the homepage of my site, but need to filter it as follows:

    It must be a unique category (so I don't have more than one from the same category showing),
    It must sort by date, so that the latest ones show first.

    I've tried the following:

    public function getCombinedLatestNews() {
          $sqlQuery = new SQLQuery();
          $sqlQuery->select = array(
             "`NewsArticle`.*"
          );
          $sqlQuery->from = array(
           "NewsArticle"
          );
          $sqlQuery->where = array(
           "NewsCategoryPageID IN (178,179,180,181,182)"
          );
          $sqlQuery->groupby = array ("NewsCategoryPageID");
          $sqlQuery->orderby = "Date DESC";
          $sqlQuery->limit = 3;

          $result = $sqlQuery->execute();

          // let Silverstripe work the magic
          $records = singleton('NewsArticle')->buildDataObjectSet($result);

          return $records ? $records : false;
       }

    But it doesn't quite work, and seems to return slightly random results.

    Has anyone got any suggestions on how I might get this working?

    1112 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.