CakePHP: Select DISTINCT in ContainableBehaviour
I am trying to select only distinct related model entries but it seems it doesn't work.
I have this:
$active_questions = $this->Question->find('all', array('conditions' => array('test_id' => $active_tests), 'fields' => array('answer_style_id'), 'contain' =>开发者_开发知识库 array(
'Answer' => array(
'fields' => array('capital_category_id'),
'CapitalCategory' => array(
'fields' => array('id', 'DISTINCT capital_id', 'DISTINCT category_id', 'delete_flag'),
'Capital' => array(
'fields' => array('id', 'delete_flag')
),
'Category' => array(
'fields' => array('id', 'delete_flag')
)
)
)
)));
But Cake seems to automatically add the associated model key, even id I specified it with a DISTINCT keyword:
Query: SELECT `CapitalCategory`.`id`, DISTINCT `CapitalCategory`.`capital_id`, DISTINCT `CapitalCategory`.`category_id`, `CapitalCategory`.`delete_flag`, `CapitalCategory`.`capital_id`, `CapitalCategory`.`category_id` FROM `capital_categories` AS `CapitalCategory` WHERE `CapitalCategory`.`id` = 217
How do I filter out only DISTINCT capitals or categories? For the current example, Cake returns 20 categories with the same id. I want only one to be returned.
Thank you.
Off the top of my head, the following may work using the 'group' option
$active_questions = $this->Question->find(
'all',
array(
'conditions' => array('Question.test_id' => $active_tests),
'fields' => array('answer_style_id'),
'contain' => array(
'Answer' => array(
'fields' => array('capital_category_id'),
'CapitalCategory' => array(
'fields' => array('id', 'capital_id', 'category_id', 'delete_flag'),
'group' => array('capital_id', 'category_id'),
'Capital' => array(
'fields' => array('id', 'delete_flag')
),
'Category' => array(
'fields' => array('id', 'delete_flag')
)
)
)
)
)
);
Why don't you put 'group' just below 'fields' and not inside 'contain', also you may have to remove 'fields' altogether.
精彩评论