简体   繁体   中英

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

I have this code in HostStatistic model:

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();
}

It works correctly if all HostStatistic records have record in Rhost, but if one or several HostStatistic records does not have Rhost record sorting does not work. I have no any exceptions but data was not sorted. I rewrite code with mongo aggregation and it works as I want. But how can I do the same with Yii2 ActiveRecord?

I came to the conclusion that in the question I gave myself the answer - mongo aggregation accomplishes what I need, and works quite stable for me.

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'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM