Cakephp DISTINCT - PullRequest
       2

Cakephp DISTINCT

7 голосов
/ 14 июля 2011

Как использовать DISTINCT для получения уникального идентификатора пользователя с наибольшим значением для total_time_driven_at_this_trip, а также для извлечения user_name из другой таблицы, отношения которой принадлежат на основе user_id?

Я пробовал это...

$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'))));

но это не работает.

Полагаю, вам нужно опуститься ниже ....

SELECT DISTINCT(user_id),`total_time_driven_at_this_trip` FROM `trip_nsws` order by `total_time_driven_at_this_trip` desc 

Ответы [ 6 ]

9 голосов
/ 27 июля 2012
// 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')
    ));

}
7 голосов
/ 02 апреля 2012

Правильный синтаксис для клавиш DISTINCT в cakephp

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

Убедитесь, что DISTINCT использует в массиве fields.

1 голос
/ 23 марта 2012

Вы можете установить его как виртуальное поле (http://book.cakephp.org/1.3/view/1608/Virtual-fields)

$this->Model->virtualFields['distinct_user'] = 'DISTINCT Model.user_id';
1 голос
/ 23 декабря 2011

Правильный синтаксис:

$this->set('tripNsws', $this->TripNsw->find('all',array('fields'=>'DISTINCT TripNsw.user_id')));
0 голосов
/ 15 июля 2012
'fields' => array('DISTINCT Model.Modelfield')

или

'fields' => array('Model.id','DISTINCT Model.Modelfield')
0 голосов
/ 15 мая 2012

Я всегда использовал GROUP BY в запросе, чтобы получить тот же результат, что и DISTINCT

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...