Justin Young Justin Young - 5 months ago 10
PHP Question

beforeFind() add conditions

I'm trying to filter EVERYTHING that's returned in my App based on a client condition. This is in my AppModel:

public function beforeFind($queryData) {
parent::beforeFind();
$queryData['conditions'] = array('client_id' => 2);
$this->log($queryData);
}


It's not filter the returned content though, but the condition info shows up in the log. What am I doing wrong?

Answer

With beforeFind() you should return the $queryData array that you have modified if you want the find to use it. This is your current problem.

public function beforeFind($queryData) {
    parent::beforeFind();
    $queryData['conditions'] = array('client_id' => 2);
    return $queryData;
}

However, you have a couple of other small issues that could cause you problems down the line.

  1. You should not set the conditions outright in your beforeFind(), but add to it. What if you are calling a find with conditions? Consider this:

    $this->MyModel->find('first', array(
        'conditions' => array(
            'MyModel.active' => 1
        )
    ));
    

    You want the find to use that condition, but also for your beforeFind() to automatically return only the result for the client_id = 2, using your beforeFind(). Unfortunately, with this line in your beforeFind():

    $queryData['conditions'] = array('client_id' => 2);
    

    You've just overwritten the conditions array completely, and lost your other condition of MyModel.active = 1.

  2. You should also ensure that you are stating which model the field in the condition belongs to. This is good practice, and future proofs your code if you have two models which have a field called client_id. You can use $this->alias to get the current model's alias, which will also allow your code to work if you have used a different alias for the model.

So your final code should be:

    public function beforeFind($queryData) {
        parent::beforeFind();
        $queryData['conditions'][$this->alias . '.client_id'] = 2;
        return $queryData;
    }
Comments