2016-07-19 100 views
-3

我一直在試圖找出了好幾天這個(我想很簡單的)事情:SQL查詢來CakePHP的翻譯

我有三個表具有以下字段:

  1. alumnes:ID ,nomcognoms
  2. grups:ID
  3. alumnesgrups:ID,alumne_id(與Alumnes.id)和grup_id(相關Grups.id)。這是一個透視表(連接表,關係表...)

我的問題是:

我應該代碼AvadiariesController.php如果我想填充一個選擇框(在add.ctp)從這個查詢結果:

SELECT 
alumnes.nomcognoms 

FROM 
alumnes_grups 

INNER JOIN grups ON 
alumnes_grups.grup_id = grups.id 

INNER JOIN alumnes ON 
alumnes_grups.alumne_id = alumnes.id 

WHERE 
alumnes_grups.grup_id = '16-17 2nB' 

ORDER BY 
alumnes.nomcognoms 

我可以從另一個表顯示領域? 我怎樣才能看到'名字'而不是'id'?

用戶Bill好心建議我的東西重寫(正確?)到:

$alumnesGrups = $this->Avadiaries->AlumnesGrups->Alumnes->find('list', 
    ['fields' => ['Alumnes.nomcognoms'], // keep the alias consistent with whatever you define in the join 
    'joins' => [['table' => 'alumnes', 
       'alias' => 'Alumnes', 
       'type' => 'INNER', 
       'conditions' => ['Alumnes.id' => 'AlumnesGrups.alumne_id']], 
     // mimic the above to join the other table 
       ['table' => 'grups', 
       'alias' => 'Grups', 
       'type' => 'INNER', 
       'conditions' => ['AlumnesGrups.grup_id' => '16-17 2nB'], 
       'order' => ['Alumnes.nomcognoms' => 'ASC']] 
       ] 
       ] 
    ); 

現在add.ctp沒有給出錯誤,但並未被應用於此條件:

'conditions' => ['AlumnesGrups.grup_id' => '16-17 2nB'] 

我只需要這個起點,所以我可以找出其他一些東西。

回答

0

我終於找到了解決辦法閱讀本document後。現在

$alumnesGrups = $this->Avadiaries->AlumnesGrups->find('all', [ 
'fields' => ['Alumnes.name'], 
'contain' =>['Alumnes', 'Grups'], 
'conditions' => ['Grups.id =' => 1] 
]); 

我的問題是,我得到{「Alumnes」:{「名」:「安吉拉·史密斯」}},而不只是簡單的「安吉拉·史密斯」。我會繼續搜索。

0

嘗試類似:

$this->AlumnesGrup->find('all', 
    array(
     'fields' => array(
      'Alumne.nomcognoms' // keep the alias consistent with whatever you define in the join 
     ), 
     'joins' => array(
      array(
       'table' => 'alumnes', 
       'alias' => 'Alumne', 
       'type' => 'INNER', 
       'conditions' => array(
        'Alumne.id = AlumnesGrup.alumne_id 
      ), 
      // mimic the above to join the other table 
     ), 
     'conditions' => array(
      'AlumnesGrup.grup_id' => '15-16 2nB' 
     ), 
     'order' => array(
      'Alumne.nomcognoms ASC' 
     ) 
    ) 
); 

爲清楚起見,我修改您的查詢了一下,是這樣的:

SELECT 
alumnes.nomcognoms 

FROM 
alumnes_grups 

INNER JOIN grups ON 
alumnes_grups.grup_id = grups.id 

INNER JOIN alumnes ON 
alumnes_grups.alumnes_id = alumnes.id 

WHERE 
alumnes_grups.grup_id = '15-16 2nB' 

ORDER BY 
alumnes.nomcognoms