php – Doctrine – 存储ArrayCollection键

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – Doctrine – 存储ArrayCollection键脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
每当我使用带有Doctrine ORM(2.3,PHP> 5.4)的ArrayCollection,并将对象值与集合中的键相关联时(例如使用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正确记住键?先谢谢你了.

这可以通过以下方式解决
/** @Entity */
class MyEntity
{
    /** @OneToMany(targetEntity="MyOtherEntity",mappedBy="mainEntity",indexBy="key") */
    private $myArray;

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

    public function addOtherEntity($key,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;
}

脚本宝典总结

以上是脚本宝典为你收集整理的php – Doctrine – 存储ArrayCollection键全部内容,希望文章能够帮你解决php – Doctrine – 存储ArrayCollection键所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: