Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp DISTINCT

Tags:

php

cakephp

How do I use DISTINCT to get unique user id with highest value for total_time_driven_at_this_trip and also pull user_name from another table which has belongsto relations based on user_id?

I tried this...

$this->set('tripNsws', $this->TripNsw->find('all',array('limit' => 20,'fields' => array('DISTINCT(TripNsw.user_id)','TripNsw.total_time_driven_at_this_trip'),'group' => array('TripNsw.user_id') ,'order' => array('TripNsw.total_time_driven_at_this_trip desc'))));

but it's not working.

I suppose you need to get below....

SELECT DISTINCT(user_id),`total_time_driven_at_this_trip` FROM `trip_nsws` order by `total_time_driven_at_this_trip` desc 
like image 559
Passionate Engineer Avatar asked Jul 14 '11 01:07

Passionate Engineer


3 Answers

// see below url

    http://book.cakephp.org/1.3/view/1018/find


 array(
    'conditions' => array('Model.field' => $thisValue), //array of conditions
    'recursive' => 1, //int
    'fields' => array('Model.field1', 'DISTINCT Model.field2'), //array of field names
    'order' => array('Model.created', 'Model.field3 DESC'), //string or array defining order
    'group' => array('Model.field'), //fields to GROUP BY
    'limit' => n, //int
    'page' => n, //int
    'offset'=>n, //int
    'callbacks' => true //other possible values are false, 'before', 'after'
)



// or try this



function some_function() {

    $total = $this->Article->find('count');

    $pending = $this->Article->find('count', array('conditions' => array('Article.status' => 'pending')));

    $authors = $this->Article->User->find('count');

    $publishedAuthors = $this->Article->find('count', array(
    'fields' => 'DISTINCT Article.user_id',
    'conditions' => array('Article.status !=' => 'pending')
    ));

}
like image 196
Abid Hussain Avatar answered Nov 18 '22 13:11

Abid Hussain


Correct Syntax for DISTINCT keywork in cakephp

$this->set('banners', $this->Banner->find('all',array('fields'=>'DISTINCT Banner.id')));

Make sure DISTINCT uses in fields array.

like image 29
Panky Avatar answered Nov 18 '22 14:11

Panky


The correct syntaxis is

$this->set('tripNsws', $this->TripNsw->find('all',array('fields'=>'DISTINCT TripNsw.user_id')));
like image 1
edwinallenz Avatar answered Nov 18 '22 12:11

edwinallenz