2012-05-24 30 views
1

我正在嘗試在我的一個表上進行查找,並且我正在動態地將hasMany關係的條件從一個模型添加到另一個模型。一切工作正常,除了Cake不會將組條件應用於查詢。如果我複製生成的查詢,並在MySQL中運行它並添加我的分組條件,它會很好地工作。我嘗試了很多東西,但都無濟於事,現在我擁有它的方式就像Cake文檔中的查找頁面設置告訴我通過設置一個組。你可以在下面找到我是如何做到的:CakePHP不會按條件應用分組

$this->Project->hasMany['ProjectTime']['conditions'] = array('user_id'=>$this->Auth->user('id'), 'date_entry >= '.$firstDay.' AND date_entry <= '.$lastDay); 
    $this->Project->hasMany['ProjectTime']['order'] = array('date_entry ASC'); 
    $this->Project->hasMany['ProjectTime']['group'] = 'ProjectTime.date_entry'; 
    $this->Project->hasMany['ProjectTime']['fields'] = array('ProjectTime.date_entry, ProjectTime.user_id, ProjectTime.project_id, SUM(ProjectTime.duration) AS durationTotal');   
    $result = $this->Project->find('all', array('conditions'=>array('Project.id IN (' . implode(",", $projectTimeArray) . ')'))); 

我試着把它直接放在模型中的hasMany數組中 - 什麼都沒有。我曾嘗試在該組周圍放置一個陣列 - 什麼都沒有。我真的很難過,所以如果有人能幫忙,我會非常感激。

回答

1

這是一個非常奇怪的方式來構建查詢:-S

可以這樣寫(假設項目的hasMany ProjectTime):

$result = $this->Project->find('all', array(
    'conditions'=>array(
     'Project.id'=>implode(",", $projectTimeArray) 
    ), 
    'joins'=>array(
     array(
      'table'=>'project_times', 
      'alias'=>'ProjectTime', 
      'type'=>'INNER', 
      'conditions'=>array(
       'ProjectTime.project_id = Project.id', 
       'ProjectTime.user_id'=>$this->Auth->user('id'), 
       'ProjectTime.date_entry >='=>$firstDay 
       'ProjectTime.date_entry <=' => $lastDay 
      ), 
      'order'=>array('ProjectTime.date_entry'=>'ASC'), 
      'group'=>array('ProjectTime.date_entry') 
     ) 
    ) 
)); 

(鍵入到編輯,未經測試;-)

+0

您不需要崩潰,CakePHP理解Project.id的數組。 – mark

1

我知道這個答案很晚,但我修改了核心以允許hasMany中的組。我不確定爲什麼CakePHP團隊做出了這樣的決定,如果任何人都可以提供洞察力,爲什麼他們有,我將不勝感激。

線:1730 /lib/Cake/Model/Datasource/DboSource.php

 case 'hasMany': 
      $assocData['fields'] = $this->fields($LinkModel, $association, $assocData['fields']); 
      if (!empty($assocData['foreignKey'])) { 
       $assocData['fields'] = array_merge($assocData['fields'], $this->fields($LinkModel, $association, array("{$association}.{$assocData['foreignKey']}"))); 
      } 

      $query = array(
       'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $Model, $LinkModel, $association, $assocData), $assocData['conditions']), 
       'fields' => array_unique($assocData['fields']), 
       'table' => $this->fullTableName($LinkModel), 
       'alias' => $association, 
       'order' => $assocData['order'], 
       'limit' => $assocData['limit'], 
       'offset' => $assocData['offset'], 
       'group' => $assocData['group'], 
      ); 

值$ assocData [ '基團']的加入到該組密鑰。