Thursday, March 31, 2011

Re: Paginate pre-ordered list

If I'm interpreting it correctly, you have a table 'likes' that has the following fields:

  user_id (unique, represents the user_id of the person who is liked)
  count (number of users who indicated that they like this user_id)

so that Like belongsTo User, and conversely, User hasOne Like. Assuming that both User and Like have the same dataSource, have you tried:

$this->paginate('User', array(
    'contain' => array('Like'),
    'conditions' => array(
        'Like.count >' => 0
    ),
    'order' => array(
        'Like.count' => 'desc',
        'Like.modified' => 'asc'
    )
);

instead of using Like::getMostLiked() then running individual queries for each user in the resulting array.

Because User hasOne Like, the ContainableBehavior uses a LEFT JOIN between User and Like, so Like.count is in the scope of the SQL query, and you should be able to use it as part of the $options['order'].  Or as an alternative, you can also try:

$this->paginate('Like', array(
    'contain' => array('User'),
    'conditions' => array(
        'Like.count >' =>  0
    ),
    'order' => array(
        'Like.count' => 'desc',
        'Like.modified' => 'asc'
    )
);

Either one should work, since there's a one-to-one relation between the two models.  And since only one SQL query is executed (instead of 1 + $limit, because you currently run 1 SQL query for Like::getMostLiked, and then individual queries for each of the user_id values), it should be a little faster and less resource-intensive.

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
 
 
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: