如何在 Yii2 中缓存 "exists" 验证

How to cache "exists" validation in Yii2

我正在尝试缓存 Yii2 存在验证的数据库调用,但不知道从哪里启动它。

因为我使用的是具有很多关系的多模型表单,所以开销有点太大了。

有什么想法吗?

Yii 不支持,你要么:

  • 扩展 ExistValidator 并在那里实现您的缓存逻辑
  • 向您的相关模型添加自定义 ActiveQuery class 并覆盖 exists()count() 方法

你最好不要。实际上,an issue on Yii2 official Github project 框架的核心开发人员之一 Alexander Makarov aka @samdark 解释了为什么缓存 ExistValidator 是个坏主意:

Exist validation isn't the kind of validation to be cached. Each second database may change its state so it should be validated just before it's saved.