Defining global conditions in Model

前端 未结 2 1196
长发绾君心
长发绾君心 2020-12-19 10:50

Is it possible to define global conditions for Model ?

I have 2 Models: User and Student. In database both of them are using table u

相关标签:
2条回答
  • 2020-12-19 11:16

    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".

    0 讨论(0)
  • 2020-12-19 11:18

    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

    0 讨论(0)
提交回复
热议问题