Wednesday, 15 September 2010

Fetch random row from group by query (mysql) in Cakephp -



Fetch random row from group by query (mysql) in Cakephp -

i have table 'activities' , columns grouped 3 of attributes. want fetch activity id randomly selected set of groups. query follows:

$act = $this->find('all', array('conditions' => $cond, 'limit' => $limit, 'fields' => array('count(*) count, activity.id id'), 'page' => $page, 'group' => $group, ));

these things tried , none of them worked. 1. create self bring together should have random records

$this->bindmodel(array( 'belongsto' => array( 'random' => array( 'classname' => 'activity', 'order' => 'rand()', 'foreignkey' => 'id', 'fields' => 'random.id' ) ) ));

this failed because rand() order appended in end randomizes fetched activities.

added bring together option

'joins' => array( array( 'table' => 'activities', 'alias' => 'random', 'type' => 'left', 'conditions' => array( 'activity.id = random.id' ), 'fields' => 'random.id', 'order' => 'rand()' )

this didn't work order value not parsed cake

tried add together condition 'activity.id >= floor(rand() * (max(activity.id) - min(activity.id)) - min(activity.id))' gave mysql error

please help me out

assuming query working:

$act = $this->find('all', array('conditions' => $cond, 'limit' => $limit, 'fields' => array('count(*) count, activity.id id'), 'page' => $page, 'group' => $group, 'order' => 'rand()', 'limit' => '1' // if want 1 random activity id ));

mysql cakephp

No comments:

Post a Comment