Skip to content

Instantly share code, notes, and snippets.

@mooror
Last active February 2, 2020 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mooror/b84dc2589f9795816cb8fb17e24e80be to your computer and use it in GitHub Desktop.
Save mooror/b84dc2589f9795816cb8fb17e24e80be to your computer and use it in GitHub Desktop.
SS4 How to sort a DataObject by COUNT of many_many relation (Updated version of http://www.silverstrip.es/blog/sort-tags-by-popularity-or-how-to-sort-a-dataobject-by-count-of-many-many-relation/)
/**
* Return a DataList of Example DataObjects sorted by the number
* of Other records they are related to
*
* Note: This method will also filter out any Example DataObjects that aren't
* related to any Other records
*
* @param integer $limit The maximum records to return
* @return DataList Filtered DataList of Example DataObjects
*/
public function getCategoryList($limit = 20)
{
$dataList = Example::get()
->setQueriedColumns(['ID', 'Title', 'Count(Example_Other_Many_Many_Table.Example_TableID)'])
->leftJoin('Example_Other_Many_Many_Table','Example_Other_Many_Many_Table.Example_TableID = Example_Table.ID')
->sort('Count(Example_Other_Many_Many_Table.Example_TableID) DESC')
->alterDataQuery(function($query){
$query->groupBy('Example_Table.ID')
->having('Count(Example_Other_Many_Many_Table.Example_TableID) > 0');
})
->limit($limit);
return $dataList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment