Improved sorting logic
Added missing _class variable
Add extra check if relation actually exists.
Typo fix