Last active
February 2, 2020 20:09
-
-
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/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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