Artur Mamedov
Artur Mamedov

Reputation: 617

CakePHP 3.x ORM get(), find() and how to disable befeoreFind()?

I use the beforeFind() callback with some conditions that must be apply in most case, but not in all. And the quesion is about this.

What are the right way for disable the beforeFind() callback?

At the moment i use this approach:

in beforeFind() i have a return $query if options default are false

if(isset($options['default']) && $options['default'] == false){
    return $query;
}

And now when i perform a find() operation, i can disable by set default option to false

$this->Articles->find()->applyOptions(['default' => false])...

But when i use get() method, i don't know how to do...

i can use findById() and applyOptions again but if there are another way i prefer.

Thanks in advance!

Upvotes: 0

Views: 538

Answers (2)

Walter Raponi
Walter Raponi

Reputation: 46

Just use

$this->Hotels->get($id, ['default' => false]); 

$options will be passed and your beforeFind will keep working :-D

Upvotes: 3

floriank
floriank

Reputation: 25698

I use the beforeFind() callback with some conditions that must be apply in most case, but not in all.

Use a custom finder instead of the beforeFind() callback and implement your logic or conditions there. Then you can chain them and use them only when you need them. I recommend you to read the manual section about them.

$this->find('all')->find('myConditions');

Example taken from the manual:

use Cake\ORM\Query;
use Cake\ORM\Table;

class ArticlesTable extends Table
{

    public function findOwnedBy(Query $query, array $options)
    {
        $user = $options['user'];
        return $query->where(['author_id' => $user->id]);
    }

}

// In a controller or table method.
$articles = TableRegistry::get('Articles');
$query = $articles->find('ownedBy', ['user' => $userEntity]);

Upvotes: 1

Related Questions