1

我们构建了一组相当复杂的 $conditions,然后使用 Paginator 进行搜索:

$this->Paginator->settings = array( 'conditions'=>$conditions, 
                      'joins'=>$joins, 
                      'limit'=>25,
                      //'fields' => array('DISTINCT (User.id)') 
                );
$resume_display_array = $this->Paginator->paginate('User');

你会看到'fields'被注释掉了。当我们取消注释该字段时,它会导致关联模型Resume从结果数组中删除(没有它,返回的每个结果都包含一个 [Resume] 键。

为什么会这样?

这是使用 DISTINCT 选项的 SQL 转储:

SELECT DISTINCT (`User`.`id`), `User`.`id` 
FROM `sw`.`users` AS `User` 
LEFT JOIN `sw`.`taggings_users` AS `TaggingUser` 
  ON (`User`.`id`= `TaggingUser`.`user_id`) 
LEFT JOIN `sw`.`taggings` AS `Tagging` 
  ON (`TaggingUser`.`tagging_id`= `Tagging`.`id`) 
LEFT JOIN `sw`.`resumes` AS `Resume` 
  ON (`Resume`.`user_id` = `User`.`id`) 
WHERE `User`.`first_name` LIKE '%jordan%' AND NOT (`Tagging`.`tag_name` = ('done')) 
LIMIT 25  

这是没有 DISTINCT 选项的 SQL 转储:

SELECT `User`.`id`, `User`.`username`, `User`.`password`, `User`.`role`, `User`.`created`, `User`.`modified`, `User`.`email`, `User`.`wordpress_user_id`, `User`.`first_name`, `User`.`last_name`, `User`.`group_id`, `Resume`.`id`, `Resume`.`user_id`, `Resume`.`wordpress_resume_id`, `Resume`.`wordpress_user_id`, `Resume`.`has_file`, `Resume`.`is_stamped`, `Resume`.`is_active`, `Resume`.`file_extension`, `Resume`.`created`, `Resume`.`modified`, `Resume`.`is_deleted` 
FROM `sw`.`users` AS `User` 
LEFT JOIN `sw`.`taggings_users` AS `TaggingUser` 
  ON (`User`.`id`= `TaggingUser`.`user_id`) 
LEFT JOIN `sw`.`taggings` AS `Tagging` 
  ON (`TaggingUser`.`tagging_id`= `Tagging`.`id`) 
LEFT JOIN `sw`.`resumes` AS `Resume` 
  ON (`Resume`.`user_id` = `User`.`id`) 
WHERE `User`.`first_name` LIKE '%jordan%' AND NOT (`Tagging`.`tag_name` = ('done')) 
LIMIT 25  

更新

这是一个 var_dump $joins

array(
    (int) 0 => array(
        'table' => 'taggings_users',
        'type' => 'LEFT',
        'alias' => 'TaggingUser',
        'conditions' => array(
            (int) 0 => 'User.id= TaggingUser.user_id'
        )
    ),
    (int) 1 => array(
        'table' => 'taggings',
        'type' => 'LEFT',
        'alias' => 'Tagging',
        'conditions' => array(
            (int) 0 => 'TaggingUser.tagging_id= Tagging.id'
        )
    )
)
4

1 回答 1

0

如果指定fields选项,则需要指定要检索的所有字段。

通过将其设置为 ONLY User.id,您就是在告诉它这是您想要返回的唯一字段。

您也可以尝试以下类似的方法(不确定这是否有效,但如果没有,您就会明白 - 您正在限制自己的结果):

'fields' => array('*', 'DISTINCT (User.id)')
于 2013-10-15T13:03:10.313 回答