Symfony mongoDB oneToMany

时间:2018-02-12 07:49:48

标签: php database mongodb symfony entity

也许以某种方式知道这个问题,

我与oneToMany有关系,保存/编辑所有okey

    /**
     * @MongoDB\ReferenceMany(targetDocument="RmaWorkerCities", cascade={"all"}, mappedBy="rmaWorker", storeAs="id", orphanRemoval=true)
     */
    protected $cities;
   /**
     * @MongoDB\ReferenceOne(targetDocument="RmaWorkers", inversedBy="cities")
     */
protected $rmaWorker;

但是当我想按城市记录搜索时,我收到了这个错误:

Cannot use reference \'cities\' in class \'App\\Document\\RmaWorkers\' for lookup or graphLookup: dbRef references are not supported.

或者它只是不起作用

我试图做的事情:

 $builder = $this->dm->createAggregationBuilder('App\Document\RmaWorkers');

    if (!empty($filters['cityId'])) {
        $builder
            ->lookup('cities')
            ->alias('cities');


        $builder->match()->field('cities.cityId')->equals($filters['cityId']);
    }

或只是

$builder
            ->field('cities.cityId')->equals($filters['cityId'])
        ;

1 个答案:

答案 0 :(得分:0)

如错误所述,查找阶段不支持“ dbRef引用”。

您的解决方法是从DBRef中提取objectId,然后您可以在查找阶段正常使用它。

本地写的,它的工作原理如下:

db.rmaWorker.aggregate([
{
    $project: { 
        cities_fk: {
          $map: { 
             input: { 
                  $map: {
                      input:"$cities",
                      in: {
                           $arrayElemAt: [{$objectToArray: "$$this"}, 1]
                      },
                  }
             },
             in: "$$this.v"}},
        }
}, 
{
    $lookup: {
        from:"cities", 
        localField:"cities_fk",
        foreignField:"_id", 
        as:"B"
    }
])

只需调整上面的示例,将其与AggregationBuilder一起使用即可。您还可以创建自定义函数来封装不同的步骤,因此它不会使您的聚合器声明混乱。类似的东西:

 $builder = $this->dm->createAggregationBuilder('App\Document\RmaWorkers');

if (!empty($filters['cityId'])) {
    $builder
        ->addFields()
        ->name('cities_fk')
        ->mapManyDBRefs()
        ->lookup('cities_fk')
        ->alias('cities');


    $builder->match()->field('cities.cityId')->equals($filters['cityId']);
}