Search code examples
phpsymfonydoctrine-orm

Method "id" for object "Doctrine\ORM\PersistentCollection" does not exist in AppBundle:Game:view.html.twig at line 26


So, I'm trying to display all of the comments belonging to a game, but for some reason, I always get this error:

Method "id" for object "Doctrine\ORM\PersistentCollection" does not exist in AppBundle:Game:view.html.twig at line 26

The getCommentsForGame looks like this

public function getCommentsForGame($game)
{
  $id = $game->getId();

    $query = $this->createQueryBuilder('game')

        ->select(
            'game.id',
            'game.title',
            'comments.id',
            'comments.content'
        )
        ->innerJoin('game.comments', 'comments')
        ->where('game.id = :id')
        ->setParameter('id', $id)
        ->getQuery();

    return $query->getResult();
} 

And then the Comment Entity:

/**
 * Id.
 *
 * @ORM\Id
 * @ORM\Column(
 *     type="integer",
 *     nullable=false,
 *     options={
 *         "unsigned" = true
 *     }
 * )
 * @ORM\GeneratedValue(strategy="IDENTITY")
 *
 * @var integer $id
 */
private $id;

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

/**
 * Games array
 *
 * @ORM\ManyToOne(targetEntity="Game", inversedBy="games")
 * @ORM\JoinColumn(name="game_id", referencedColumnName="id")
 * )
 *
 * @var \Doctrine\Common\Collections\ArrayCollection $games
 */
 protected $games;

And Game Entity:

/**
 * Comments array
 *
 * @ORM\OneToMany(
 *      targetEntity="AppBundle\Entity\Comment",
 *    mappedBy="games"
 * )
 */
protected $comments; 

In Twig I'm using this:

       {{ game.comments.id }} 

Where's my error?


Solution

  • game.comments is returning a Collection and a collection doesn't have an ID. You have to loop through the Collection and get the ID for each Comment:

    {% for comment in game.comments %}
        {{ comment.id }}
    {% endfor %}
    

    Try using dump() on game.comments and game.comments[0] to see what I mean.