Cakephp 2.x beforeFind related models

How do you extend the beforeFind () condition to related models?

Taking for example a school, course and term (which should be a class, but this word is reserved in php), this is the code used in the course model:

/**
 * beforeFind method
 *
 * Filters by the school (based on the url)
 * @param  array  $query The find query
 * @return array  $query The query with the added condition
 */
public function beforeFind($query = array()) {
    parent::beforeFind($query);
    $query['conditions'] = (is_array($query['conditions'])) ? $query['conditions'] : array();
    $this->School->id = CakeSession::read('School');
    $conditions = array(get_class($this).'.school_id' => $this->School->id);
    $query['conditions'] = array_merge($query['conditions'], $conditions);
    return $query;
}

When I receive courses, the conditions are correct:

$this->Course->contain = array('School');
$this->Course->find('all');

This returns all courses for the current school based on the session. When I enter classes, the school condition does not apply:

$this->Term->contain = array('Course');
$this->Term->find('all');

It returns me all terms with all courses without beforeFind conditions on the course model. Is it possible to add a beforeFind clause to a parent model that extends to its child models without having to code beforeFind for each child model?

+4
source share
2 answers

, , Cake 2.x. Github, beforeFind ​​ Cake 3.0 ( ), , .

+3

, , beforeFind() Cake 2.x. afterFind():

public function afterFind($results = array(), $primary = false) {
    foreach($results as $x=>$items) {
        foreach($items as $model=>$item) {
            if( isset($item['was_deleted']) AND !empty($item['was_deleted']) ) {
                unset($results[$x]);
            }
        }
    }

    return $results;
}
0

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


All Articles