문제

How do you propagate a beforeFind() condition into associated models?

Taking for example a School, Course, and Term (which should be a Class, but that word is reserved in php), this is the code used on 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'm fetching courses, the conditions apply correctly:

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

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

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

It returns me all the terms, with all the courses, without the beforeFind conditions on the Course model. Is it possible to add a beforeFind condition on a parent model that propagates to its children models, without having to code the beforeFind on every children model?

도움이 되었습니까?

해결책

Unfortunately, I don't think this is possible in Cake 2.x. If you look at this ticket from Github, the issue of using beforeFind from associated models was fixed in Cake 3.0 (at the bottom of the page) but there is no solution for older versions, except manually changing the core files.

다른 팁

As already replied, this you need is not possible using beforeFind() in Cake 2.x. However, you can filter the items in 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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top