2015-06-23 34 views
0

我有很深的關聯,我想知道是否有可能通過包含在一個BTM協會現場訂購結果:排序在belongsToMany協會現場

$modeles = $this->Caracteristiques 
     ->find() 
     ->contain(['ModeleElements.ModeleOuvrages' => function ($q) { 
      return $q 
       ->where([ 
        'ModeleOuvrages.couche_id' => 2, 
        'ModeleOuvrages.compte_client_id' => $this->Auth->user('compte_client_id') 
       ]); 
     }]); 

這裏是我的查詢,我想要一個結果「ModeleOuvrages」協會中的字段「nom」排序。

是否有可能通過「ModeleOuvrages.nom」獲得所有「caracteristiques」排序?

編輯:我這樣做:

$modeleOuvrages = $this->ModeleOuvrages 
     ->find() 
     ->where([ 
      'couche_id' => 2, 
      'compte_client_id' => $this->Auth->user('compte_client_id') 
     ]) 
     ->select([ 
      'ModeleOuvrages.nom', 
      'ModeleElements.nom', 
      'Caracteristiques.nom', 
      'Caracteristiques.type' 
     ]) 
     ->matching('ModeleElements.Caracteristiques') 
     ->order(['ModeleOuvrages.nom', 'ModeleElements.nom', 'Caracteristiques.nom']); 

,而且運作良好。我們也可以用更詳細的包含來做到這一點。

+0

「where」子句是否足以保證發現任何給定的「Characteristique」不會有更多且不少於一個「ModeleOuvrage」?如果沒有,那麼我不知道你會如何排序。如果是這樣,那麼我認爲你想要的是使用「匹配」而不是「包含」,類似於[我問的問題]的答案(http://stackoverflow.com/questions/30718606/translating-query-involving -join表從 - cakephp的-1-3至30721698分之3#30721698)。 –

回答

1

是的,在使用matching('Deep.Nested.Table')時,您將能夠對該表的任何列進行排序。

請記住,匹配會創建INNER JOIN s,並且它可能會在結果中重複行。您可以使用$query->distinct(['MainTable.id'])刪除重複項。