简体   繁体   English

我正在尝试从OnetoMany关系中读取“教义收藏”项目,但找不到方法。

[英]I'm trying to read a Doctrine Collection items from a OnetoMany relationship and I cannot find how.

I'm using Symfony2. 我正在使用Symfony2。

This is my object Player: 这是我的对象播放器:

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="player")
 */
class Player
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    protected $name;

    protected $urlAvatar;

    /**
     * @ORM\Column(type="integer")
     */
    protected $coins;

    /**
     * @ORM\Column(type="integer")
     */
    protected $money;

    /**
     * @ORM\OneToMany(targetEntity="Mercenary", mappedBy="player")
     */
    protected $mercenaries;

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

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set coins
     *
     * @param integer $coins
     */
    public function setCoins($coins)
    {
        $this->coins = $coins;
    }

    /**
     * Get coins
     *
     * @return integer 
     */
    public function getCoins()
    {
        return $this->coins;
    }

    /**
     * Set money
     *
     * @param integer $money
     */
    public function setMoney($money)
    {
        $this->money = $money;
    }

    /**
     * Get money
     *
     * @return integer 
     */
    public function getMoney()
    {
        return $this->money;
    }

    /**
     * Add mercenaries
     *
     * @param IFZ\TowerofDimensionsBundle\Entity\Mercenary $mercenaries
     */
    public function addMercenary(\IFZ\TowerofDimensionsBundle\Entity\Mercenary $mercenaries)
    {
        $this->mercenaries[] = $mercenaries;
    }

    /**
     * Get mercenaries
     *
     * @return Doctrine\Common\Collections\Collection 
     */
    public function getMercenaries()
    {
        return $this->mercenaries;
    }
}

I want to read the Information from Mercenaries but I cannot find how. 我想阅读《雇佣兵信息》,但找不到方法。 It returns a Doctrine Collection, but I cannot go forward that and obtain all the items from the collection. 它返回了一个教义集合,但是我不能继续前进并从集合中获取所有项目。 I don't want to filter them, I just want to get all the items. 我不想过滤它们,我只想获取所有项目。 Thanks for read. 感谢您的阅读。

You can iterate over an ArrayCollection just like you would do with an array: 您可以像遍历数组一样遍历ArrayCollection

foreach ($player->getMercenaries() as $mercenary) {
    // do whatever you want with $mercenary
}

Or in Twig: 或在Twig中:

{% for mercenary in player.mercenaries %}
    {# do whatever you want with mercenary #}
{% endfor %}

You can also get an array from a collection: 您还可以从集合中获取数组:

$mercenariesArray = $player->getMercenaries()->toArray();

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

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