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

Php 是否修改beforeFind回调中所需的可包含字段?,php,cakephp,callback,behavior,Php,Cakephp,Callback,Behavior,在我的CakePHP1.2.5应用程序中,我有一个Profile模型,属于User模型。用户模型有一个username字段,在配置文件模型上执行find()时,我希望始终自动检索User.username的值。我认为修改我的概要文件模型的beforeFind()方法以自动包含所需字段是有意义的 以下是我试图做的: public function beforeFind($queryData) { // determine if the username data was already r

在我的CakePHP1.2.5应用程序中,我有一个
Profile
模型,属于
User
模型。用户模型有一个
username
字段,在配置文件模型上执行
find()
时,我希望始终自动检索
User.username
的值。我认为修改我的概要文件模型的
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;
}
我可以看到,
$queryData['contain']
的值正在正确更新,但是没有检索用户名数据。我研究了
find()
方法的CakePHP核心代码,发现
beforeFind()
回调是在所有行为的回调之后调用的,这意味着Containable在我能够修改它之前已经对
$queryData['contain']
的值做了它需要做的事情


我怎样才能在不破坏核心的情况下解决这个问题呢?

我解决了这个问题,下面是我的答案,以防有人有同样的问题。无法在beforeFind中指定可包含字段,因为所有行为的beforeFind()方法都是在模型的beforeFind()方法之前调用的

因此,我有必要直接在概要文件模型上修改
find()
方法,以便附加自定义的containable字段

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);
}

马特,我相信这是一个很好的解决方案。我使用的是CakePHP2.0.4,我打算只获取用户模型数据

仅作记录,为用户模型设置actsAs

class User extends AppModel {
    public $name = 'User';
    public $belongsTo = array('Role');
    public $actsAs = array('Containable');
    ...
然后,我以这种方式重写find方法:

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
    $this->contain();
    return parent::find($conditions, $fields, $order, $recursive);
}
或者,如果打算获取配置文件数据,例如:

public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
    $this->contain(array('Profile'));
    return parent::find($conditions, $fields, $order, $recursive);
}

谢谢我也对此感到困惑,不知道beforeFind()修改是否“太晚了”。的确是这样。