【问题标题】:Symfony2 fetch data from entity with OneToMany relationSymfony2 从具有 OneToMany 关系的实体中获取数据
【发布时间】:2015-12-03 20:36:00
【问题描述】:

我有两个实体:AdAdPhoto。它们有关系:OneToMany(许多 AdPhoto 到一个广告)。 在坚持之后,我尝试通过方法Ad::getPhoto()Ad获取AdPhoto,但是我得到了PersistentCollection类,我不知道如何处理它。

帮助我了解如何将所有相关的 AdPhoto 转换为 Ad。

实体广告:

namespace AdBundle\Entity;

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

/**
 * Ad
 *
 * @ORM\Table(name="Ad")
 * @ORM\Entity
 */
class Ad
{
...
    /**
     * @ORM\OneToMany(targetEntity="AdBundle\Entity\AdPhoto", mappedBy="id")
     */
    private $photo;
...
}

实体广告照片:

namespace AdBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * AdPhoto
 *
 * @ORM\Table(name="AdPhoto")
 * @ORM\Entity
 */
class AdPhoto
{
    ...    
    /**
     * @ORM\ManyToOne(targetEntity="AdBundle\Entity\Ad", inversedBy="photo")
     * @ORM\JoinColumn(name="ad", referencedColumnName="id")
     */
    private $ad;
...
}

在控制器中:

$ad = $this->getDoctrine()->getRepository('AdBundle:Ad')
            ->findOneBy(array(
                'id' => $id
            ));

        var_dump($ad->getPhoto());

        return $this->render('AdBundle:Default:view.html.twig', array(
            'ad' => $ad
        ));

【问题讨论】:

  • 编辑问题并输入您尝试过的代码

标签: symfony doctrine


【解决方案1】:

您可以像通过常规数组一样循环遍历 twig 中的数组集合。如果你想在 php 代码中使用它作为数组,你可以使用

$photos = $ad->getPhotos()->toArray();

因为 add 可以有很多照片,所以最好使用 $photos 而不是 $photo。

【讨论】:

  • 非常感谢,我应该早上试试。将 $photo 重命名为 $photos 这是一个很好的提议。谢谢!
【解决方案2】:

Ivan Toncev 的答案很棒,但您可能还想知道一些额外的事情来让事情更容易理解。

PersistentCollection 确实具有您需要的值。当您记录它们时,您只是看不到它。不知道为什么。

您可以尝试以下方法来检查是否确实存在数据:

$ad->getPhotos()->count(); // Counts the amount of items (rows).

count($ad->getPhotos()); // Same as above.
// Loop trough all photo's.
for ($i = 0; $i < count($ad->getPhotos()); $i++) {

    // A single photo!
    $photo = $ad->getPhotos()[$i];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    相关资源
    最近更新 更多