2012-08-29 89 views
1

我正在處理在CakePHP 2框架上運行的項目。在這個應用程序,我有:CakePHP找到2 HABTM關係

型號:

Wallnote, User, Group 

關係:

Group HABTM User 
Wallnote HABTM User 
Wallnote HABTM Group 

表:

wallnotes 

- id 
- user_id (owner id) 
- ... 

users_wallnotes 

- user_id 
- wallnote_id 

groups_wallnotes 

- group_id 
- wallnote_id 

groups_users 

- group_id 
- user_id 

我使用的關係 「Wallnote HABTM用戶」 和「 Wallnote HABTM Group「作爲過濾器,即user_id/group_id(6)wallnote_id(10)意味着,id 10的牆紙將是vis IBLE用於用戶ID爲6,分別對所有用戶在組ID爲6.

我想找到所有wallnotes匹配這些條件:

  1. 登錄的用戶是這個wallnote的擁有者或
  2. wallnote用登錄的用戶共享 - >在表users_wallnotes記錄OR
  3. wallnote用一些基團共享和登錄用戶是該組的成員

這是可以做到這使用find()函數?

感謝您的回答。

回答

1

您有兩個角色:組和用戶。 這是非常困難的用戶來處理它和集團獨立... 我認爲標準方法是你必須爲每個用戶和組獨特的作用,爲處理這一點,你必須有這個表:

wallnotes 
- id 
- user_id (owner id) 
- ... 

roles 
- id 
- user_id 
- group_id 
(each rows in this table have group_id or user_id , no both of them) 

roles_wallnotes 
- id 
- role_id 
- wallnote_id 

當你創建一個用戶(或組),您必須爲其創建一個角色。所以所有組和用戶現在都有唯一的ID。

比如你有2組(1,2 IDS)和4個用戶(含1,2,3,4 IDS),則:

users : 
|id|name | 
---|------ 
1 | user1 
2 | user2 
3 | user3 
4 | user4 

groups : 

|id|name | 
---|------ 
1 | group1 
2 | group2 

roles : 
|id| user_id | group_id | 
---|---------|----------| 
1 | 1  | null | 
2 | 2  | null | 
3 | 3  | null | 
4 | 4  | null | 
5 | null | 1  | 
6 | null | 2  | 

現在你必須有這樣的關係:

Role hasOne Group 
Role hasOne User 
Wallnote HABTM Role 

使用此解決方案,您可以輕鬆使用查找功能來檢索您需要的數據...