Yii 2.0 ActiveRecord inverseOf

Yii 2.0 introduced a new feature to its ActiveRecord class, the inverse relation.  The documentation does a decent job at explaining its purpose – to prevent an unneeded SQL call from being executed and the instantiation of a new object, when in reality, the current object that is performing the lookup is the same object that would be found with that unneeded SQL call.  The optimization is much appreciated and in one project, this new relation has cut down on the SQL being executed and potential errors being introduced.

However, what the documentation does not make clear, as referenced in issue 7316, is that, in most cases, the inverse relation should only be defined for one side of the relationship.  For example, let’s take the documentation’s example of an order having exactly one customer, and customers having many orders.  In this example, the inverseOf should only be defined within the Customer class’ order relation.  This is because the order can only have one customer, so no SQL is required to determine what the correct customer will be.

What if we had an inverseOf relation defined in the opposite direction from the Order class’ customer relation?  The inverseOf relation would tell the customer class that this one order is the only order the customer has!  Obviously, not correct.

To determine if you should use the inverseOf relation, just ask yourself when writing the relation, does the other class have a ‘hasOne’ relation to this class?  If it does, you should be OK to use the inverseOf relation.

Share this page:
  • Facebook
  • Twitter
  • Reddit
  • Google Bookmarks
  • email
  • Print
  • RSS
  • Digg
  • StumbleUpon
  • del.icio.us
  • Slashdot
  • Technorati
  • Tumblr

Steven Michaels

Steven Michaels specializes in PHP web applications utilizing MediaWiki, WordPress, Yii Framework and others. He is an open source contributor and leads development for both of Hollow Developers' internal projects, HollowGame and SpeechEase.

Facebook comments:

Leave a Reply