如何在 Yii2 MongoDB ActiveRecord 中按关系字段对记录进行排序,如果某些记录中的 getter


How to sort records by relation field in Yii2 MongoDB ActiveRecord if getter from some records returns null?

我在 HostStatistic 模型中有以下代码:

public function getRhost()
{
    return $this->hasOne(Rhost::className(), ['host' => 'host']);
}
public static function getPage($sort = null, $offset = null, $limit = null)
{
    if (!$sort) {
        $sort = ['rhost.last_time' => SORT_DESC];
    }
    $offset = (int)$offset;
    $limit = (int)$limit;
    if (!$limit) {
        $limit = self::DEFAULT_LIMIT;
    }
    return self::find()
        ->with('rhost')
        ->orderBy($sort)
        ->offset($offset)
        ->limit($limit)
        ->all();
}
如果所有 HostStatistical 记录在 Rhost

中都有记录,则它工作正常,但如果一个或多个 HostStatistical 记录没有 Rhost 记录排序,则无法正常工作。我没有任何例外,但数据没有排序。我用 mongo 聚合重写代码,它可以按照我想要的方式工作。但是我怎样才能用 Yii2 ActiveRecord 做同样的事情呢?

我得出的结论是,在问题中我给了自己答案 - mongo 聚合满足了我需要的,并且对我来说非常稳定。

public static function getPage($sort = null, $offset = null, $limit = null)
{
    if (!$sort) {
        $sort = ['rhost.last_time' => -1];
    }
    $offset = (int)$offset;
    $limit = (int)$limit;
    if (!$limit) {
        $limit = self::DEFAULT_LIMIT;
    }
    $aggregate = [
        [
            '$lookup' => [
                'from' => 'rhosts',
                'localField' => 'host',
                'foreignField' => 'host',
                'as' => 'rhost',
            ]
        ],
        [
            '$sort' => $sort,
        ],
        [
            '$limit' => (int)$limit + (int)$offset,
        ],
        [
            '$skip' => (int)$offset,
        ],
    ];
    $mongoCollection = self::getCollection()->mongoCollection;
    return $mongoCollection->aggregate($aggregate)['result'];
}