How to determine relations programmatically

In Yii 1.x, model classes had a method relations() that you could override to define relations. There is no easy way to get this out of the box with Yii 2.0 from what I can tell. Gii generates relations as getter methods that return hasOne() or hasMany() , so assuming you know the relations ahead of time you can still get related records, however there is no way that I can tell to ask a model to give you all defined relations. I’m just curious if this is something that will ever be added back in? In the mean time, I’ve experimented with the three approaches as a workaround:

  1. created a generator based on the current gii model generator that inserts creates a static class array that contains a list of the hasOne and hasMany relation names

  2. created a base model that extends ActiveRecord that has a method that can reflectively inspect the class annotations / doc comments to look for properties declared there, and returns whether they’re hasOne or hasMany based on whether or not they’re declasred as an array or not

  3. another method in class mentioned in #2 that steps through all getter methods defined in the class, inspects the source code of each method definition and determines if hasOne() or hasMany() is called. If so, determines that it is a relation

#2 and #3 are potentially very fragile, though. and #1 is something that could (and arguably) should be optionally implemented in the core gii model generator.

Here is a link to my model class:

https://gist.github.com/nathanejohnson/b524bca9ba6304380639

Thoughts?

Yii 2 does not keep record of relations like it was Yii 1 hasOne relationship is normal ActiveQuery object just like Model::find()