ActiveRecord: has many: orderBy related table of related - how?

Hi guys,

In my user table, I have implemented the following relation:

 /**
      * @return \yii\db\ActiveQuery
      */
     public function getUserHasNotificationEvents() {
         return $this->hasMany(\app\models\UserHasNotificationEvent::className(), 
                 ['tbl_user_id' => 'id']));
     }

The UserHasNotificationEvent table has also a related table called UserHasNotificationEventType

Now, I need a orderby like this (in turn of the following related table):

**
     * @return \yii\db\ActiveQuery
     */
    public function getUserHasNotificationEvents() {
        return $this->hasMany(\app\models\UserHasNotificationEvent::className(), 
                ['tbl_user_id' => 'id'])
                ->orderBy(['tblUserHasNotificationEventType.name' => SORT_ASC]);
    }

Does anyone have an idea how to do this?

Thanks a lot!
Toby

Hi @strtob

I hope something like this will work.

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUserEvents() {
        return $this->hasMany(UserEvent::className(), ['user_id' => 'id'])
                ->leftJoin('event_type', 'user_event.type_id = event_type.id')
                ->orderBy(['event_type.name' => SORT_ASC]);
    }

Not tested, though.

Active Record > Dynamic Relational Query
(Working with Databases: Active Record | The Definitive Guide to Yii 2.0 | Yii PHP Framework)

great - thanks a lot! I’ll try - leftJoin, sure - this make sense :wink: