Php 是的。如何在MongoDB/ActiveQuery中使用聚合?
如何在MongoDB/ActiveQuery中构建聚合?例如,如果使用MySQL/ActiveQuery,我的查询如下所示:Php 是的。如何在MongoDB/ActiveQuery中使用聚合?,php,mongodb,yii2,Php,Mongodb,Yii2,如何在MongoDB/ActiveQuery中构建聚合?例如,如果使用MySQL/ActiveQuery,我的查询如下所示: $query = new Query(); $query->select(['name', '(field1 + field2) AS calculated_field']); 如何在MongoDB/ActiveQuery中构建此查询 (我正在使用ActiveDataProvider的查询。我不仅需要显示字段,还需要按此字段排序)您可以在Yi2(getter和se
$query = new Query();
$query->select(['name', '(field1 + field2) AS calculated_field']);
如何在MongoDB/ActiveQuery中构建此查询
(我正在使用ActiveDataProvider的查询。我不仅需要显示字段,还需要按此字段排序)您可以在Yi2(getter和setter)中为模型使用属性,这样您就不必在sql查询中硬编码它。 例如,您有一个模型“Human”,它有两列:name、姓氏。 通过写作
$human = Human::findOne(0);
echo $human->fullname;
您希望聚合$human->name和$human->姓氏。因此,您可以在模型代码中执行以下操作
* @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;
}
...
}
仅此而已,当您调用$human->fullname时,它将在您的视图中返回getFullname()函数值,只需添加:
$collection = Yii::$app->mongodb->getCollection('collection1');
$join = $collection->aggregate([[
'$lookup' => [
'from' => 'collection2',
'localField' => 'same_field',
'foreignField' => 'same_field',
'as' => 'collection1'
]
]]);
我不仅需要显示字段,还需要按此字段排序。@Аааааааааааааааааа1072。此示例仅适用于MySql,但不适用于MongDb