在我的CakePHP 1.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()回调所有行为回调之后被调用,这意味着中容纳已经做了什么,它需要与$queryData['contain']的价值做我能够修改之前

我怎样才能解决这个没有黑客核心?

有帮助吗?

解决方案

我解决了它,所以这里是我的情况下,任何人的答案具有相同的并发症。中可容纳字段不能在beforeFind指定因为所有行为beforeFind()方法被称为的现有以模型的beforeFind()方法。

因此,有必要对我直接修改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);
}

其他提示

马特,我相信这是一个很好的解决方案。我使用CakePHP的2.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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top