0

I'm trying to cache the db calls for Yii2 exists validation, but can't work out where to initiate it.

Because I'm using a multi-model form with a lot of relations, the overhead is getting a little too much.

Any ideas?

Tom Horwood
  • 398
  • 3
  • 13
  • This is not supported by Yii, you either have to extend the ExistValidator and implement your caching logic there or add a custom ActiveQuery class to your model in question and override the exists() and count() methods – Nader Roua Nov 13 '17 at 03:03
  • @Nader I thought as much - just thought I'd ask in case I'd missed something. If you want to add your response as an answer I'll mark it as accepted. – Tom Horwood Nov 13 '17 at 04:02

2 Answers2

3

You'd better not. Actually, there is an issue on Yii2 official Github project where one of the framework's core developers, Alexander Makarov aka @samdark, explains why caching ExistValidator is a bad idea:

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.

Yaronius
  • 784
  • 3
  • 17
  • 34
  • 1
    I agree generally, but this was a specific circumstance in which a tradeoff needed to be made between certainty and performance. Due to the nature of the specific tables in question, the tradeoff was worth the extra performance. I think the general approach is correct, but careful use of an exception to the rule was needed in this case. – Tom Horwood Jan 09 '20 at 10:54
2

This is not supported by Yii, you either have to :

  • Extend the ExistValidator and implement your caching logic there
  • Add a custom ActiveQuery class to your model in question and override the exists() and count() methods
Nader Roua
  • 611
  • 5
  • 9