Yii: Ajax sorting on STAT relations


/ Published in: PHP
Save to your folder(s)

When setting up the AJAX click to sort links for your index pages, it's nice to be able to sort on STAT and related data.

To get related data sorting in my CListView, I ended up having to forget about using "together" and "with" in my search function, and instead let everything lazy load. The number of queries explode, which sucks.

For handling your STAT relations, you can manually write SQL that runs when the sorting links are clicked. So this is pretty much duplicate code and sloppy, but it works.

The query below recreated this relation that exists on the model:
<code>
'followersCount'=>array(self::STAT,'GraphEdge','end','condition'=>'status=1'),
</code>

The naming here doesn't matter, the relation and sortable attribute are unfortunately independent. This was written for CListView but probably works with CGridView as well.
Don't forget to add followers_count to your List View's sortable attributes array.


Copy this code and paste it in your HTML
  1. //AT THE END OF YOUR MODEL SEARCH FUNCTION
  2.  
  3. return new CActiveDataProvider($this, array(
  4. 'criteria'=>$criteria,
  5. 'pagination' => array(
  6. 'pageSize' =>15,
  7. ),
  8. 'sort'=>array(
  9. 'defaultOrder'=> array('id'=>CSort::SORT_ASC), //Can add more here, but arrows show
  10.  
  11. 'attributes'=>array(
  12. 'id',
  13. 'followers_count'=>array(
  14. 'desc' => '(SELECT SUM(graph_edge.id) FROM graph_edge WHERE graph_edge.end = t.id AND graph_edge.status = 1) DESC',
  15. 'asc' => '(SELECT count(graph_edge.id) FROM graph_edge WHERE graph_edge.end = t.id AND graph_edge.status = 1) ASC', //This query should match your STAT relationship
  16. ),
  17. 'create_time'=>array(
  18. 'desc' => 't.create_time DESC',
  19. 'asc' => 't.create_time ASC',
  20.  
  21. ),
  22. 'page_title',
  23. ),
  24. ),
  25. ));

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.