BeforeFind () add conditions

I am trying to filter out ALL that is returned in my application based on client status. This is in my AppModel:

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

It does not filter the returned content, but status information appears in the log. What am I doing wrong?

+4
source share
3 answers

With beforeFind (), you must return the $queryData array that you changed if you want 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 minor problems that can cause problems on the line.

  • You should not set conditions directly in your beforeFind () file, but add . What if you call a find with conditions? Consider this:

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

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

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

    You have just completely rewritten the conditions array and lost another condition MyModel.active = 1 .

  • You must also make sure that you indicate which model the field in the condition refers to. This is good practice, and future proof of your code, if you have two models that have a field called client_id . You can use $this->alias to get the current model alias, which will also allow your code to work if you 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; } 
+6
source
 public function beforeFind($queryData) { if(parent::beforeFind($queryData) !== false) { $defaultConditions = array($this->alias . '.client_id' => 2); $queryData['conditions'] = array_merge($defaultConditions, $queryData['conditions']); return $queryData; } return false; } 

I followed the BadHorsie solution and distracted it more:

  • Checking the result of the beforeFind parent before continuing
  • Using array_merge in a different order so that the default conditions are really default
  • Using $ this-> alias, so you don't need to change the class name
+1
source

try changing to:

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

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


All Articles