【问题标题】:Doctrine - Store ArrayCollection keysDoctrine - 存储 ArrayCollection 键
【发布时间】:2013-06-25 17:29:12
【问题描述】:

每当我将 ArrayCollection 与 Doctrine ORM(2.3,PHP > 5.4)一起使用,并将对象值与集合中的键相关联(例如使用 set 方法时),值都会正确存储在数据库中.但是当我想从实体中检索集合时,键不会被检索,而是使用数字索引。

例如,如果我有以下课程:

/** @Entity */
class MyEntity
{
    /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity") */
    private $myArray;

    public function __construct()
    {
        $this->myArray = new ArrayCollection();
    }

    public function addOtherEntity($key, $value)
    {
        $this->myArray->set($key, $value);
    }

    ...
}

/** @Entity */
class MyOtherEntity
{
    /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */
    private $mainEntity;
    ...
}

set 方法可以正常工作,但是当我检索信息时,$myArray 中的键消失了。

如何让 ORM 正确记住密钥?提前谢谢你。

【问题讨论】:

    标签: php orm doctrine-orm


    【解决方案1】:

    通过以下方式解决:

    /** @Entity */
    class MyEntity
    {
        /** @OneToMany(targetEntity="MyOtherEntity", mappedBy="mainEntity", indexBy="key") */
        private $myArray;
    
        public function __construct()
        {
            $this->myArray = new ArrayCollection();
        }
    
        public function addOtherEntity($key, $value)
        {
            $this->myArray->set($key, $value);
        }
    
        ...
    }
    
    /** @Entity */
    class MyOtherEntity
    {
        /** @ManyToOne(targetEntity="MyEntity", inversedBy="myArray") */
        private $mainEntity;
    
        /** @Column(name="MyOtherTable_Key", type="string", unique=true, length=50)
        private $key;
        ...
    }
    

    您的数据库架构中还需要MyOtherTable_Key,以便它可以正确存储密钥。

    请记住始终将对象键设置到属性中。一种方法是在构造函数中声明键。

    public function __construct($key)
    {
        $this->key = $key;
    }
    

    【讨论】:

    • 这是获得键控响应的解决方案吗?
    • 等待什么响应?查询一?
    • 措辞糟糕。当将实体序列化为 json 时,数组集合由元素值作为键。顺便说一句。谢谢。
    • 哦。如果您在集合上调用toArray(),您将拥有一个键值数组,其中的键与存储在数据库中的键相同,所以是的,这将在序列化时向 JS 脚本返回一个键值数组。如果您需要一个可序列化的类,但请始终记住使其实现JsonSerializable,这是 PHP 默认库的一部分。顺便说一句,如果它不适合你,请回答,以便我可以给你另一个解决方案。
    猜你喜欢
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 2016-06-08
    相关资源
    最近更新 更多