2014-04-23 71 views
0

我有以下表格:CakePHP的複雜關係

teams(id, name) 
team_users(id, team_id, user_id) 
users (id, username) 
projects (id, project_name, team_id) 

團隊的hasMany用戶,用戶的hasMany團隊,一個項目屬於關聯一個團隊。

如果我調用$ this-> User-> find();它返回用戶和他所屬團隊的信息。

我想要做的是,我想要計算他與之相關的項目。含義:

John Doe是Team X和Y的成員.X有2個項目,Y有3個項目。我想將項目數量返回爲5,某種虛擬領域。可能嗎?

回答

1

如果你已經正確設置你的模型關係這個查詢是所有你需要:

$this->User->virtualFields = array('total_projects' => 'COUNT(*)'); 
$user_projects = $this->User->find('all',array('fields' => array('total_projects', '*'))); 

//$user_projects["User"]["total_projects"] -> this will result to 5 base on your question above or you can debug this by: debug($user_projects) so you can see the content of the array