2017-02-07 26 views
0

如何在MongoDB/ActiveQuery中构建聚合?例如,如果使用MySQL/ActiveQuery,我的查询如下所示:Yii2。如何在MongoDB/ActiveQuery中使用聚合?

$query = new Query(); 
$query->select(['name', '(field1 + field2) AS calculated_field']); 

如何在MongoDB/ActiveQuery中构建此查询?

(我使用的查询ActiveDataProvider。我需要的不仅是显示领域,需要排序这个领域太)

回答

0

您可以Yii2(getter和setter)的模型中使用的属性,让你不必在sql查询中对其进行硬编码。 例如,你有一些模型“人”,有两列:名字,姓氏。 通过写

$human = Human::findOne(0); 
echo $human->fullname; 

你想要聚合人 - $> name和$人 - >姓。所以,那么你可以做的型号代码下面

* @property string $name (from database) 
* @property string $surname (from database) 
* @property string $fullname 
class Human extends \yii\db\ActiveRecord 
{ 
... 
public function getFullname() { 
     return $this->name.' '.$this->surname; 
    } 
... 
} 

这一切,当你调用人 - $>全名,它将返回getFullname()函数值

+0

我需要的不仅是显示领域,需要对于这个领域来说也是如此。 –

+0

@АндрейЛитвиненко,那么你可以简单地重复自定义activerecord列给定的步骤http://stackoverflow.com/questions/28578057/sort-and-filter-data-in-gridview-yii2-where-column-is-not-在数据库中 – Yerke

+0

谢谢。此示例仅适用于MySql,但不适用于MongDb –