为什么我使用Doctrine 2& amp;获取数组的数组Symfony 2数据转换器? [英] Why am I getting an Array of an Array with Doctrine 2 & Symfony 2 Data Transformer?

查看:71
本文介绍了为什么我使用Doctrine 2& amp;获取数组的数组Symfony 2数据转换器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了 Symfony 2数据转换器,用户输入以逗号分隔的字符串列表,并将其转换为Doctrine期望的ArrayCollection。现在问题出在 transform()上,它将把 ArrayCollection 转换为逗号分隔的字符串。

I have setup a Symfony 2 Data Transformer that will allow the user to enter a comma separated list of string and convert that to an ArrayCollection which Doctrine expects. Now the problem is in the transform() where it will convert an ArrayCollection to a comma separated string.

/**
 * Transform ArrayCollection of Tag's into Comma Separated string
 * 
 * @param ArrayCollection $tags
 * @return string
 */
public function transform($tags) {
    if ($tags == null) 
        return '';

    $tagNames = array();
    var_dump($tags);
    $tags->map(function($tag) use(&$tagNames) {
        $tagNames[] = $tag->getName();
    });
    return implode(', ', $tagNames);
}

$ tags 外观像:

object(Doctrine\Common\Collections\ArrayCollection)#222 (1) {
  ["_elements":"Doctrine\Common\Collections\ArrayCollection":private]=>
  array(1) {
    [0]=>
    array(1) {
      [0]=>
      object(JM\BlogBundle\Entity\Tag)#53 (3) {
        ["id":"JM\BlogBundle\Entity\Tag":private]=>
        int(1)
        ["name":"JM\BlogBundle\Entity\Tag":private]=>
        string(4) "blog"
        ["description":"JM\BlogBundle\Entity\Tag":private]=>
        string(0) ""
      }
    }
  }
}

注意它在一个数组中的一个数组。为什么会这样?

Notice its an array in an array. Why is that?

更新:数据转换器代码-> http://pastie.org/3004780

UPDATE: data transformer code -> http://pastie.org/3004780

推荐答案

在您的 reverseTransform()方法,您正在搜索带有以下行的单个标签:

It looks like in your reverseTransform() method, you're searching for a single tag with this line:

$tag = $this->em->getRepository('JM\BlogBundle\Entity\Tag')->findBy(array('name' => $strTag));

但是, findBy()始终会返回ArrayCollection,即使仅找到一个结果。尝试使用 findOneBy(),它将仅返回没有ArrayCollection包装器的结果。

However, findBy() will always return an ArrayCollection, even if only one result is found. Try using findOneBy(), which will simply return the result without the ArrayCollection wrapper.

此外,对于某些之前的版本艺术,请查看 FPNTagBundle 可标记教义扩展。特别是, TagManager 可能具有您可以在自己的代码中实现的一些优化。

Also, for some prior art, check out the FPNTagBundle and Taggable Doctrine Extension. In particular, the TagManager might have some optimizations that you can implement in your own code.

这篇关于为什么我使用Doctrine 2& amp;获取数组的数组Symfony 2数据转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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