Symfony 在 prepersist 上将数据添加到对象 [英] Symfony add data to object on pre persist

查看:16
本文介绍了Symfony 在 prepersist 上将数据添加到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建文档的表单.一方面,我可以添加名称和描述,然后我可以选择创建的文档所属的一个或多个机构.每个代理都被分配到一个特定市场(总共有7个市场,所以一个市场可以有几个代理但一个代理只属于一个市场!)我想要实现的是prePersist"功能,它会自动将正确的市场(取决于选择的代理机构的数量)添加到文档中.

I have a form to create documents. On the one side I can add names and descriptions and next to that I can select one or several agencies to whom the created document belongs. Each of the agencies is assigned to one specific market (there are 7 markets in total, so one market can have several agencies but one agency belongs only to one market!) What I want to achieve is a "prePersist" function which automatically adds the correct market(s) (depending on the number of agencies selected) to the document.

我的文档实体有两个实体(市场和机构)以及相应的 getter 和 setter:

My document entity has the two entities (markets and agencies) with the according getters and setters:

 /**
* @ORMManyToMany(targetEntity="AppBundleEntityMarket", inversedBy="uploadProfiles", cascade={"persist"})
* @ORMJoinTable(name="document_uploadprofile_markets",
*   joinColumns={@ORMJoinColumn(name="uploadprofile_id", referencedColumnName="id")},
*   inverseJoinColumns={@ORMJoinColumn(name="market_id", referencedColumnName="id")})
**/
private $markets;

        /**
         * @ORMManyToMany(targetEntity="AppBundleEntityAgency", inversedBy="uploadProfiles", cascade={"persist"})
         * @ORMJoinTable(name="document_uploadprofile_agencies",
         *   joinColumns={@ORMJoinColumn(name="uploadprofile_id", referencedColumnName="id")},
         *   inverseJoinColumns={@ORMJoinColumn(name="iata8", referencedColumnName="iata8")})
         **/
        private $agencies;
  public function __construct()
    {
        $this->agencies = new DoctrineCommonCollectionsArrayCollection();
    $this->markets = new DoctrineCommonCollectionsArrayCollection();

}

       /**
 * Add market
 *
 * @param AppBundleEntityMarket $market
 *
 * @return UploadProfile
 */
public function addMarket(AppBundleEntityMarket $market)
{
    $this->markets[] = $market;

    return $this;
}

/**
 * Remove market
 *
 * @param AppBundleEntityMarket $market
 */
public function removeMarket(AppBundleEntityMarket $market)
{
    $this->markets->removeElement($market);
}

/**
 * Get markets
 *
 * @return DoctrineCommonCollectionsCollection
 */
public function getMarkets()
{
    return $this->markets;
}
  /**
     * Add agency
     *
     * @param AppBundleEntityAgency $agency
     *
     * @return UploadProfile
     */
    public function addAgency(AppBundleEntityAgency $agency)
    {
        $this->agencies[] = $agency;

        return $this;
    }

    /**
     * Remove agency
     *
     * @param AppBundleEntityAgency $agency
     */
    public function removeAgency(AppBundleEntityAgency $agency)
    {
        $this->agencies->removeElement($agency);
    }

    /**
     * Get agencies
     *
     * @return DoctrineCommonCollectionsCollection
     */
    public function getAgencies()
    {
        return $this->agencies;
    }

我知道我可以将 prePersist 函数添加到我的文档实体并尝试编写我想要实现的代码,但我认为这不起作用,因为我需要这样的东西:

I know that I can add the prePersist function to my document entity and try to code what I want to achieve but I don't think that's working because I need something like that:

  foreach($document->getAgencies() as $agency) {
      $document->setMarket($em->getRepository('AppBundle:Agency')->getMarket($agency));
     }

我什至不确定 foreach 循环是否正确,因为(到目前为止)结果始终为空.我已经在这里问过这个主题的问题:Symfony 在 CreateController 中为 Arraycollection 使用 setter

I'm not even sure whether that foreach loop is correct since (so far) the result is always null. I've already asked a question to that topic here: Symfony use setter for Arraycollection in CreateController

我还尝试编写一个自己的存储库函数来从我的代理实体获取所有不同的市场,但到目前为止这也不起作用.

I've also tried to write an own repository function to get all the distinct markets from my agency entity but so far that's not working either.

另一个想法是我的表单类中的 POST_SUBMIT 事件侦听器,但到目前为止这对我来说也没有意义.

Another idea was a POST_SUBMIT event listener in my form class but so far that didn't make sense to me either.

有什么想法吗?如果需要更多代码,请告诉我!

Any ideas? If more code is needed, let me know!

编辑我编辑并更改了上面的代码,以便在我的市场和文档之间建立多对多关系.然后我尝试的是,将 prePersist 函数添加到我的文档实体中,它实际上工作正常,同时仍然具有 OneToMany 关系(它总是覆盖以前的市场,但现在没关系)我现在正在尝试编辑该函数,以便可以将多个市场添加到文档中.我有两个想法,但都没有成功:

edit I edited and changed my code above in order to have a manytomany relationship between my markets and documents. What I then tried is, adding the prePersist function to my document entity and it actually worked fine while still having the OneToMany relationship (it was just always overwriting the previous market, but that doesn't matter now) I'm now trying to edit that function so that several markets can be added to the document. Two ideas I had, but they both didn't work out:

if(count($this->getAgencies()) > 0){
      foreach($this->getAgencies() as $agency) {
        $this->addMarket($agency->getMarket());
      }
}

--> 市场总是空的

if(count($this->getAgencies()) > 0){
      $upId = rtrim($this->getId(),"_up");
      $query = $em->createQuery("SELECT DISTINCT (a.market) FROM UserBundleEntityUser u JOIN u.agencies a WHERE u.id = $userId");
      $marketIds = $query->getResult();

      $em = $this->getDoctrine ()->getManager ();
      $repository = $this->getDoctrine()
      ->getRepository('AppBundle:Market');
      $markets = $repository->findOneById($marketIds);
      $this->addMarket($markets);
    }
  }

更新

这是我的文档实体中的 prepersist 函数,然后是 getMarkets() 函数,这已在其中一条评论中提出.我将名称改为 addMarkets 而不是 getMarkets

here is my prepersist function within my document entity and then the getMarkets() function, that has been suggested in one of the comments. I changed the name to addMarkets instead of getMarkets

/**
    * @ORMPrePersist
    */
    public function prePersist() {
if(count($this->getAgencies()) > 0){
      foreach($this->getAgencies() as $agency) {
        $this->addMarkets($agency->getMarket());
      }
    }
  }

public function addMarkets(AppBundleEntityMarket $market)
  {
      $markets = array();
      foreach($this->agencies as $agency) {
          $market = $agency->getMarket();
          $id     = $market->getId();

          // Skip duplicates
          if (isset($markets['id'])) {
              continue;
          }

          $markets[$id] = $market;
      }

      return $markets;
  }

另一种方法

所以我再次编辑它,现在我的功能看起来像这样

so I edited it again, now my function looks like that

$markets = $this->getMarkets();
if(count($this->getAgencies()) > 0){
  foreach($this->getAgencies() as $agency) {
    if(!$this->markets->contains($markets)) {
      $this->addMarket($agency->getMarket());
    }
    return;
    dump($markets);
  }
}

我认为这可能会消除我的重复,但它没有......知道为什么吗?

I thought that this might work to eliminate my duplicates but it does not.. any idea why?

推荐答案

如果我理解你所说的正确,我相信 Documents 不应该有对 Markets 的引用全部.但只引用Agency.

If I understand what you said correctly, I believe Documents should not have a reference to Markets at all. But only references Agency.

Document 将与 AgencyManyToMany 关系,仅此而已.

A Document will have a ManyToMany relation with Agency and that's it.

然后在 Document 中您可以执行以下操作:

Then in Document you can do something like:

public function getMarkets()
{
    $markets = array();
    foreach($this->agencies as $agency) {
        $market = $agency->getMarket();
        $id     = $market->getId();

        // Skip duplicates
        if (isset($markets[id]) {
            continue;
        }

        $markets[$id] = $market;
    }

    return $markets;
}

这篇关于Symfony 在 prepersist 上将数据添加到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆