0

我已经在 StackOverflow 上搜索并阅读了 Doctrine 文档的相应章节(http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/index.html)但找不到我在找什么。

我正在使用 Doctrine MongoDB v1.1 和 MongoDB v3.0.14 数据库使用 Symfony v2.8 制作的 API。

我有两个不同的文档:“Spot”和“Feature”。“Spot”包含文档“Feature”的集合,具有 ReferenceMany 关系:

// Spot document declaration

/**
 * @var \Transversal\SessionBundle\Document\Feature
 * @MongoDB\ReferenceMany(strategy="set", targetDocument="Transversal\SessionBundle\Document\Feature", sort={"uploadDate"="asc"})
 * @Serializer\Expose
 */
protected $features = array();

我正在处理 Spot 创建路由/控制器,我需要在其中发送 Spot 名称、描述和要添加到Spot 的现有功能列表。

我现在要做的是在请求的正文中发送名称、描述和一组功能 ID。然后,在控制器中,我循环遍历这个数组,并且对于每个 id 我:

  • 通过其 id 从 db 获取 Feature 的实例(因此每次迭代一个 db 请求)
  • $spot->addFeature()通过我的方法将其添加到 Spot 对象

然后我坚持并刷新以保存新创建的点。这是我的控制器方法的代码(我修改了代码以使其更具可读性):

 * @Rest\Post("")
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   * @throws BosHttpException
   */
  public function createAction()
  {
    $spot = new Spot();
    $request = $this->getCurrentRequest();

    // retrieve the name and description for the new spot here
    $form = $this->createForm(SpotType::class, $spot);
    $form->handleRequest($request);

    $content = $request->getContent();
    $params = "";
    if (!empty($content)) {
      $params = json_decode($content, true);
    }

    $document_manager = $this->getDocumentManager();
    $featureIds = $params['featureIds'];
    foreach ($featuresIds as $featureId) {
      $feature = $document_manager->find('Transversal\SessionBundle\Document\Feature', $featureId);
      $spot->addFeature($feature);
    }

    $document_manager = $this->getDocumentManager();
    $document_manager->persist($spot);
    $document_manager->flush();

    return $this->getOutputView("Spot creation - succeed", Codes::HTTP_CREATED, $this->formatResponse(null, true));

  }

以下是 Spot.php 文件中 addFeature() 的代码:

/**
 * Add feature
 *
 * @param \Transversal\SessionBundle\Document\Feature $feature
 */
public function addFeature(\Transversal\SessionBundle\Document\Feature $feature)
{
    $this->features[] = $feature;
}

这意味着如果我有一个包含 20 个功能 id 的数组,我的 foreach 循环将请求我的数据库的 20 倍,我知道这不是一个可行的解决方案(我知道我可能可以使用一个请求来获取它们,但这不是我正在寻找)。

有没有办法在知道有引用的情况下将功能分配给 Spot 而不必生成它们的实例并请求我的数据库?

在此先感谢您的帮助!

4

1 回答 1

0

这是一个示例,说明如何使用 @ParamConverter 仅传递 $feature 的 id 而不是对象

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

/**
 * @ParamConverter("feature", class="YourBundle:Feature")
 */
public function addFeature(\Transversal\SessionBundle\Document\Feature $feature){
  $this->features[] = $feature;
}

这意味着如果你让这样的代码

foreach($featuresIds as $featureId) {  
  $spot->addFeature($featureId);
}

也会起作用,因为教义应该认识到您作为参数传递的 id 是“特征”实体的 id。无论如何,ORM 也在进行查询以获取对象,您可以尝试比较时间。

于 2017-07-24T18:59:39.317 回答