方法“id"for object "DoctrineORM persistentcollecti


Method "id" for object "DoctrineORMPersistentCollection" does not exist in AppBundle:Game:view.html.twig at line 26

所以,我试图显示属于游戏的所有评论,但由于某种原因,我总是得到这个错误:

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

getCommentsForGame看起来像这样

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();
} 

然后是注释实体:

/**
 * 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; 

在Twig中,我使用这个:

       {{ game.comments.id }} 

我的错误在哪里?

game.comments返回一个集合,集合没有ID。您必须遍历Collection并获取每个Comment的ID:

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

尝试在game.commentsgame.comments[0]上使用dump()来了解我的意思。

您可以在树枝配置中设置strict_variables: false这修复了我的问题