我在嘗試創建一個很好的解決方案時有點困難,該解決方案將我的應用中的任何記錄分配給用戶或組,然後根據需要過濾該模型到這些任務。CakePHP將記錄分配給用戶:可重用的方法
我想出了下面的分配模型:
Assignment
-id
-assignedto_key
-assignedto_model (either User or Group [hasMany/belongsTo is between User and Group])
-foreign_key
-foreign_model
到目前爲止好。現在我希望能夠將我的應用程序中的任何記錄分配給整個組或一組單個用戶。
例如:
Assignment
-id = 1 (I'm actually using UUIDs)
-assignedto_key = 1
-assignedto_model = User (so this would be assigned to User.id = 1)
-foreign_key = 1
-foreign_model = Painting
Assignment
-id = 2 (I'm actually using UUIDs)
-assignedto_key = 1
-assignedto_model = Group (so this would be assigned to any User with group_id = 1)
-foreign_key = 1
-foreign_model = Painting
Therefore: User 1 can now access the Painting 1. Furthermore, ANY user with group_id = 1 can also access Painting 1.
到目前爲止好。創建邏輯使管理員能夠進入記錄(例如繪畫)並選擇應該能夠看到的組/用戶,我毫不費力。
然而,當我失去的時候我要過濾的數據:
基本上,我需要能夠記錄只返回給用戶,他們有機會獲得。
目前,我正在考慮將此視爲一種行爲,我會將其附加到所有「Assignable」模型上。
public function beforeFind(Model &$model, $query)
{
// Let's imagine that $model is of type Painting
// I can only think of the following solution:
$Assignment = ClassRegistry::init('Assignment');
$assignedIDs = $Assignment->find('all', array('fields'=> array('id'), 'conditions' => array(
'Assignment.foreign_model' => $model->alias,
'or' => array(
array('Assignment.foreign_model' => 'User', 'Assignment.foreign_key' => AuthComponent::user('id')),
array('Assignment.foreign_model' => 'Group', 'Assignment.foreign_key' => AuthComponent::user('group_id'))
)
)));
$ids = Set::extract('{n}.' . $this->alias . '.id', $assignedIDs);
$query['conditions'][] = array($this->alias . '.id' => $ids);
}
以上將獲得當前模型中的所有賦值,並且僅在這些賦值中進行查詢。但是這對我來說似乎完全沒有效率。
有沒有人有任何指示我如何才能實現這樣的功能?
非常感謝,我期待着您的回覆。作爲一個側面說明 - 我不認爲我在這種情況下尋找ACL,因爲我只希望返回過濾結果 - 但我可能錯誤地認爲ACL不是在這種情況下是正確的選擇
感謝您指出Polymorphic - 它絕對是實現這種動態關係的好方法。但是,在這種情況下,我相信它更像是一種「雙重多態」關係?或者我也可能完全不瞭解 - 如果是這樣的話,我會道歉! 問題是,該表應該屬於(要麼)用戶或組AND屬於任何其他模型。 無論如何,非常感謝您指出一個! :-) – 2012-02-12 23:22:41