Changing valid fields needed for beforeFind callback?

In my CakePHP 1.2.5 application, I have a model Profilethat belongs to the model User. The user model has a field username, and when executed find()in the profile model, I always want to automatically get the value User.username. I believe that it would be advisable to change my model model method beforeFind()to automatically contain the desired field.

Here I tried to do:

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

I see that the value $queryData['contain']is being updated correctly, but the username data is not retrieved. I looked at the main CakePHP code for the method find(), and I found that the callback beforeFind()is called after all the Behaviors callbacks, which means that Containable already did what it needed to do with the value $queryData['contain']before I was able to change it.

How can I get around this without cracking the kernel?

+3
source share
2 answers

, , - . beforeFind, Behaviors 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);
}
+6

, . 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);
}
+1

Source: https://habr.com/ru/post/1720516/


All Articles