CakePHP 3.x ORM get()、find() 以及如何禁用 befeoreFind()?
CakePHP 3.x ORM get(), find() and how to disable befeoreFind()?
我将 beforeFind() 回调与一些必须在大多数情况下应用但并非在所有情况下都适用的条件一起使用。问题是关于这个的。
禁用 beforeFind() 回调的正确方法是什么?
目前我使用这种方法:
在 beforeFind() 我有一个 return $query 如果选项默认为 false
if(isset($options['default']) && $options['default'] == false){
return $query;
}
现在当我执行 find() 操作时,我可以通过将默认选项设置为 false 来禁用
$this->Articles->find()->applyOptions(['default' => false])...
但是当我使用 get() 方法时,我不知道该怎么做...
我可以再次使用 findById() 和 applyOptions 但如果有其他方法我更喜欢。
提前致谢!
I use the beforeFind() callback with some conditions that must be apply in most case, but not in all.
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]);
只需使用
$this->Hotels->get($id, ['default' => false]);
$options 将被传递,你的 beforeFind 将继续工作:-D
我将 beforeFind() 回调与一些必须在大多数情况下应用但并非在所有情况下都适用的条件一起使用。问题是关于这个的。
禁用 beforeFind() 回调的正确方法是什么?
目前我使用这种方法:
在 beforeFind() 我有一个 return $query 如果选项默认为 false
if(isset($options['default']) && $options['default'] == false){
return $query;
}
现在当我执行 find() 操作时,我可以通过将默认选项设置为 false 来禁用
$this->Articles->find()->applyOptions(['default' => false])...
但是当我使用 get() 方法时,我不知道该怎么做...
我可以再次使用 findById() 和 applyOptions 但如果有其他方法我更喜欢。
提前致谢!
I use the beforeFind() callback with some conditions that must be apply in most case, but not in all.
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]);
只需使用
$this->Hotels->get($id, ['default' => false]);
$options 将被传递,你的 beforeFind 将继续工作:-D