【问题标题】:CakePHP beforeFind causing resetAssociations, preventing ContainableBehaviorCakePHP beforeFind 导致 resetAssociations,防止 ContainableBehavior
【发布时间】:2014-05-23 02:33:00
【问题描述】:

在我的用户模型中,我有函数 beforeFind,它使用从关联模型 (TenantsUser) 中提取的数据添加条件。

问题是当它与 ContainableBehavior 结合使用时。 首先,当调用 find 时,会调用 ContainableBehaviors 设置例程,该例程会修改 User 的关联(如预期的那样)。 然后,在我的 User/beforeFilter 函数中,我调用 TenantsUser 来执行另一个 find() 调用。但是,在 find 调用结束时,它会重置所有相关模型(包括用户)的关联,这会重置 ContainableBehavior 已完成的关联构建,因此我的 find 返回所有关联,而不是 Contains 中指定的关联。

知道如何解决这个问题吗?

【问题讨论】:

    标签: cakephp-2.4


    【解决方案1】:

    如果您可以发布一些包含您所看到的数据集的代码并解释您希望看到的内容,那么它会更容易为您提供帮助。没有这个,基本上是不可能排除故障的。我假设您已经在 Internet 上搜索了未成功的答案,这意味着您的问题可能是新问题,因此更多信息至关重要。请务必在关联定义中包含您的模型文件。

    您还提到使用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 关联,并在链接表上进行查找(如果您正在链接 TenantUserTenantsUser 表上执行find)。

    【讨论】:

      【解决方案2】:

      我最终解除绑定和重新绑定模型以解决我的问题,以下代码在 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'))
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-12
        • 2011-07-23
        • 1970-01-01
        相关资源
        最近更新 更多