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!
答案 0 :(得分:3)
只需使用
$this->Hotels->get($id, ['default' => false]);
$ options将被传递,你的beforeFind将继续工作:-D
答案 1 :(得分:1)
我使用beforeFind()回调,其中一些条件在大多数情况下必须适用,但不是全部。
Use a custom finder而不是beforeFind()回调并在那里实现你的逻辑或条件。然后你可以链接它们,只在你需要时使用它们。我建议你阅读有关它们的手册部分。
$this->find('all')->find('myConditions');
手册中的示例:
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]);