Created
October 13, 2017 09:40
-
-
Save arturmamedov/9460e0b54ac16730143dfda31e2d91cb to your computer and use it in GitHub Desktop.
CakePHP - beforeFind() callback with default conditions and possibility to disable it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function beforeFind($event, $query, $options, $primary) | |
{ | |
// if query builder have ->applyOptions(['default' => false]) not use default conditions and return query | |
if (isset($options['default']) && $options['default'] == false) { | |
return $query; | |
} | |
// default conditions | |
$query->where([ 'visible' => 1 ]); | |
$query->order([ 'sort' => 'ASC' ]); | |
return $query; | |
} |
For disabel it from Controller on selecting use ->applyOptions(['default' => false])
example:
// beforeFind() will be apply: `visible = 1 ORDER BY sort ASC`
$tips = TableRegistry::get('Tips')->find()->where(['site_id' => $this->projectId])->limit(4)->all();
// beforeFind() will not be apply
$tips = TableRegistry::get('Tips')->find()->applyOptions(['default' => false])->where(['site_id' => $this->projectId])->limit(4)->all();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://book.cakephp.org/3.0/en/orm/table-objects.html