简体   繁体   English

Doctrine2多对多不返回数组

[英]Doctrine2 Many to Many doesn't return array

If I have the following class defined, 如果我定义了以下类别,

class Category {

    /**
     *
     * @var integer $id
     * @Column(name="id", type="integer",nullable=false)
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

     /**
     *
     * @ManyToMany(targetEntity="Tag")
     * @JoinColumn(onDelete="SET NULL")
     */
    protected $tags;
}

Shouldn't I be able to get all the tags associated to this category by: 我是否应该能够通过以下方式获取与此类别相关的所有标签:

$categoryTags = $category->getTags();

The object in $categoryTags after the above assignment is of the type Doctrine\\ORM\\PersistentCollection while I expect it to be an array. 上述分配后,$ categoryTags中的对象的类型为Doctrine \\ ORM \\ PersistentCollection,而我希望它是一个数组。

I added the association values in category_tag table manually with sql commands, but I can see that they are valid. 我使用sql命令手动在category_tag表中添加了关联值,但是我看到它们是有效的。

My Tags class looks like this: 我的标签类如下所示:

class Tag extends Tag{

    /**
     *
     * @var integer $id
     * @Column(name="id", type="integer",nullable=false)
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
    protected $id;


    /**
     * @Column(type="string",length=60,nullable=false)
     * @var string
     */
    protected $tag;

}

Doctrine does not return simple arrays for associated entity collections. Doctrine不会为关联的实体集合返回简单的数组。 Rather, it returns implementations of Doctrine\\Common\\Collections\\Collection . 而是返回Doctrine\\Common\\Collections\\Collection

You can use these as you would an array as they extend the Countable , IteratorAggregate and ArrayAccess interfaces. 您可以像使用数组一样使用它们,因为它们扩展了CountableIteratorAggregateArrayAccess接口。

If you really need an array (and I can't think of a reason why), you can use the toArray() method. 如果确实需要数组(我想不出原因),则可以使用toArray()方法。

Please read the documentation to understand why Doctrine does not use simple arrays 请阅读文档以了解为什么Doctrine不使用简单数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM