2016-06-08 67 views
1

使用CakePHP 3.x,我有3個模型:StudentProfile,Diploma1和Diploma2。多重匹配()和包含(),條件相關記錄計數

  • StudentProfile的hasMany Diploma1
  • StudentProfile的hasMany Diploma2

Diploma1具有整數 「狀態」 字段。

我需要得到哪些StudentProfiles:

  • 有相關的一個(或多個)Diploma1其中Diploma1.state = 2 或
  • 有一個(或多個)Diploma2(上Diploma2領域沒有條件)

我需要用我的StudentProfiles檢索匹配的Diploma1和Diploma2。

我使用搜索和分頁程序組件,因此我必須使用一個查詢來執行此操作。

現在,我心中已經能夠做得到第一部分:

$query = $this->StudentProfiles 
    ->find('search', $this->StudentProfiles->filterParams($this->request->query)) 
    ->contain(['Diploma1' => function ($q) { 
     return $q->where(['Diploma1.state' => 2]); 
    }]) 
    ->matching('Diploma1', function($q) { 
     return $q->where(['Diploma1.state' => 2]); 
    }) 
    ->distinct(['StudentProfiles.id']) 
    ; 

    $this->set('studentProfiles', $this->paginate($query)); 

結合匹配和包含允許我補充的條件,並得到相關Diploma1(據我所知)。

現在我還需要得到所有StudentProfiles與相關Diploma2,這是我卡住的地方。如果我添加

->contain(['Diploma2']) 

...我的查詢,我只得到Diploma2爲具有匹配Diploma1(其中狀態= 2),但我不明白,只有相關Diploma2 StudentProfiles StudentProfiles(不匹配Diploma1 ),這是完全正常的。

所以我有2個問題:

  • 我怎樣纔能有一個相關的Diploma2所有StudentProfiles(?即使用count(...)> 0,也許增加一個條件)
  • 我怎麼能將此與條件(狀態= 2)的匹配子句結合起來?

我希望這是明確的。 感謝

回答

0

稍微不同的方法,但也許它可以幫助

$query = $this->Profile->find(); 

$query->select([ 
    'Profile.id', 
    'Profile.name', 
    'D1.id', 
    'D1.name', 
    'D1.status', 
    'D1.profile_id', 
    'D2.id', 
    'D2.name', 
    'D2.status', 
    'D2.profile_id', 
    'd1c' => 'COUNT(D1.id)', 
    'd2c' => 'COUNT(D2.id)', 
]); 
$query->contain([ 
    'D1' => function($q) { 
     $q->where(['D1.status' => 2]); 
     return $q; 
    }, 
    'D2' 
]); 
$query->leftJoinWith('D1', function($q) { 
    return $q->where(['D1.status' => 2]); 
}); 
$query->leftJoinWith('D2', function($q) { 
    return $q; 
}); 
$query->having(function($q) { 
    return $q->or_([ 
     'd1c >' => 0, 
     'd2c >' => 0, 
    ]); 

}); 
$query->group('Profile.id'); 

我不能真正得到contain創建一個連接,所以我不得不添加這些leftJoinWith

+0

有趣,我給這是一個嘗試儘快,謝謝! – Flo

+0

對我的第一次測試非常有用:),非常感謝這個「帶蛋糕查詢」的課程!我只是不明白爲什麼我們需要離開JoinWith和包含,但它的工作原理。 – Flo

+0

@Flo'包含'它像一個不同的範圍,所以'主要查詢'甚至不知道關於'contains'的數據,這就是爲什麼你需要使用'join'而不是'contains'。 –

相關問題