We have some code that needs to run on our ActiveRecord ‘Town’ whenever it is loaded.
If we load it like this, we can use afterFind to do this:
However, if we load it through a relation in the User active record, afterFind doesn’t get called.
Are we doing something wrong? What’s the best solution?
For anyone with the same issue:
afterFind() does not run until the model data has been fetched from a database query.
$town = Town::model()->findByPk(1);
This gets the model data for the Town table.
If you then try to access $town->user, the User model data will be selected from the database in a separate query, and afterFind() will execute on the User class.
This is called lazy loading.
If you want afterFind() to execute on the User model when you select the Town, you need to specify the join:
$town = Town::model()->with('user')->findByPk(1);
Just to clarify, the correct syntax for the afterFind() method is:
protected function afterFind()
// Your code here