Search code examples
activerecordyii2yii2-model

Yii2: how to order activeRecord relation query by related field?


I want to execute this query:

$topics = ForumTopic::find()
            ->with([                
                'lastPost' => function($query) {
                    $query->select(['id', 'ctime']);
                },
            ])
            ->orderBy('lastPost.ctime DESC')
            ->all();

Relation declared in ForumTopic like this:

public function getLastPost()
{
    return $this->hasOne(ForumPost::className(), ['id' => 'lastPostId']);
}

But my query fails (because yii2 make all queries separate and don't join tables). Is any way to achive my purpose by yii2 activeRecord?


Solution

  • So, just for clarification, the right answer is:

    $topics = ForumTopic::find()
                ->alias('t')
                ->select(['t.*','l.ctime lastPostCtime'])
                ->joinWith([
                    'lastPost l' => function($query) {
                        $query->select(['l.id', 'l.ctime', 'l.userId', 'l.guestName']);
                    },
                ])
                ->orderBy('lastPostCtime DESC')
                ->all();