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

时间:2009-10-19 22:50:50

标签: php cakephp callback behavior

在我的CakePHP 1.2.5应用程序中,我有一个属于Profile模型的User模型。用户模型具有username字段,在Profile模型上执行find()时,我也希望始终自动检索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;
}

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

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

2 个答案:

答案 0 :(得分:6)

我解决了,所以这是我的答案,以防任何人有同样的复杂情况。无法在beforeFind中指定可包含的字段,因为所有行为的beforeFind()方法都被称为先前到模型的beforeFind()方法。

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

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

答案 1 :(得分:1)

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

仅为记录,设置为用户模型的actAs

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);
}
相关问题