2014-05-23 56 views
0

在我的用戶模型中,我有beforeFind函數,它添加了從關聯模型(TenantsUser)中提取數據的條件。CakePHP beforeFind導致resetAssociations,阻止ContainableBehavior

問題在於何時將其與ContainableBehavior結合使用。 首先,當調用find時,將調用ContainableBehaviors設置例程來修改用戶的關聯(如預期的那樣)。 然後,在我的User/beforeFilter函數中,我調用TenantsUser執行另一個find()調用。然而,在查找調用結束時,它會重置所有相關模型的關聯(用戶包括在內),並重置ContainableBehavior完成的關聯構建,所以我的find將返回所有關聯,而不是Contains中指定的關聯。

有關如何解決此問題的任何想法?

回答

0

如果您可以在您看到的數據集中發佈一些代碼,並說明您期望看到的內容,那麼將更容易爲您提供幫助。沒有這個,基本上不可能排除故障。我假設你已經在互聯網上搜索失敗的答案,這意味着你的問題可能是新的,所以更多的信息是至關重要的。確保包含您的模型文件和關聯定義。

另外你還提到使用beforeFind然後beforeFilter;這是一個錯字還是你使用這兩個回調?

您是否閱讀過bindModel功能?

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly

這就是說,我總是發現中可容納的行爲是非常反直覺的。如果您只是在尋找一些可以使用CakePHP內置功能的工具,請嘗試使用hasMany through關聯,並在鏈接表上進行查找(如果您鏈接的是TenantUser,那麼可以在TenantsUser上執行find表)。

0

我結束瞭解除綁定並重新綁定模型來解決我的問題,下面的代碼是內beforeFind()

// If this function is being called with ContainableBehavior being used, then the associations of User 
// have already been adjusted to perform the query correctly. However, after find() functions are executed, 
// models, and their associated models have their associations reset to defaults. 
// Because we execute TenantsUser->find by calling the function below, TenantsUser will reset the associations 
// within the User model thereby destroying all the work that ContainableBehavior did. 
// For this reason, before calling TenantsUser->find(), we unbind the User Model from the TenantsUser Model, which means 
// that the Users associations are NOT reset. 
$this->TenantsUser->unbindModel(
     array('belongsTo' => array('User')), 
     false // We have to force the unbind to remain, otherwise the associations will be reset. 
    ); 

$user_ids = $this->TenantsUser->getUserIdsForTenant($this->getCurrentTenantId(), $tenants_users_statuses); 

// Rebind the model. 
$this->TenantsUser->bindModel(
    array('belongsTo' => array('User')) 
); 
相關問題