Defining global conditions in Model

2019-02-17 21:52发布

Is it possible to define global conditions for Model ?

I have 2 Models: User and Student. In database both of them are using table users but each student has set parent_id to its owner (which is set in the same table) while each user has parent_id set to Null.

When I use for example

$this->find('all'); 

in Student Model I want to force Cake to return only those records from database table users where parent_id != Null .

So the question is - can I define somehow global conditions in the Model? Something like that:

public $conditions = array('Student.parent_id !=' => Null);

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-17 22:33

Use beforeFind

You can use before find to modify all queries issued for a model:

function beforeFind(array $queryData) {
    $queryData['conditions'][]['NOT'][$this->alias . '.parent_id'] = null;
    return $queryData;
}

Be careful using this technique to not overwrite existing conditions (note the extra []) otherwise a query for "not parent_id 2" becomes "not parent_id null".

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-17 22:37

you could use the afterFind callback to alter your finds in the model

public function afterFind($results, $primary = false) {
    foreach ($results as $key => $val) {
        if ($val['parent_id'] == NULL) { //no parent_id set then remove that part of the results
           unset($results[$key]);
        }
    }
    return $results;
}

reference: http://book.cakephp.org/2.0/en/models/callback-methods.html

查看更多
登录 后发表回答