修改beforeFind回调中所需的可包含字段?

Mat*_*ins 3 php cakephp behavior callback

在我的CakePHP 1.2.5应用程序中,我有一个属于Profile模型的User模型.User模型有一个username字段,当find()在Profile模型上执行a 时,我想总是自动检索值User.username.我认为修改我的Profile模型的beforeFind()方法以自动包含所需的字段是有意义的.

这是我试图做的事情:

public function beforeFind($queryData) {
    // determine if the username data was already requested to be included in the return data via 'User.username' or 'User' => array('username').
    $hasUserData  = isset($queryData['contain']) && in_array("User.{$this->User->displayField}", $queryData['contain']);
    $hasUserData |= isset($queryData['contain']['User']) && in_array($this->User->displayField, $queryData['contain']['User']);

    // request the the username data be included if it hasn't already been requested by the calling method
    if (!$hasUserData) {
        $queryData['contain']['User'][] = $this->User->displayField;
    }

    return $queryData;
}
Run Code Online (Sandbox Code Playgroud)

我可以看到$queryData['contain']正确更新的值,但未检索用户名数据.我查看了该find()方法的CakePHP核心代码,我发现beforeFind()在所有Behaviors的回调之后调用了回调,这意味着Containable已经完成了$queryData['contain']在我能够修改它之前需要做的事情.

如何在不破解核心的情况下解决这个问题?

Mat*_*ins 6

我解决了,所以这是我的答案,以防任何人有同样的复杂情况.中可容纳的字段不能在beforeFind指定,因为所有的行为beforeFind()方法被调用之前到模型的beforeFind()方法.

因此,我有必要find()直接在Profile模型上修改方法,以便附加我的自定义可包含字段.

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
    $this->contain("{$this->User->alias}.{$this->User->displayField}");
    return parent::find($conditions, $fields, $order, $recursive);
}
Run Code Online (Sandbox Code Playgroud)