所以,我试图显示属于游戏的所有评论,但由于某种原因,我总是得到这个错误:
Method "id" for object "DoctrineORMPersistentCollection" 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.
*
* @ORMId
* @ORMColumn(
* type="integer",
* nullable=false,
* options={
* "unsigned" = true
* }
* )
* @ORMGeneratedValue(strategy="IDENTITY")
*
* @var integer $id
*/
private $id;
/**
* Get id.
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Games array
*
* @ORMManyToOne(targetEntity="Game", inversedBy="games")
* @ORMJoinColumn(name="game_id", referencedColumnName="id")
* )
*
* @var DoctrineCommonCollectionsArrayCollection $games
*/
protected $games;
And Game Entity:
/**
* Comments array
*
* @ORMOneToMany(
* targetEntity="AppBundleEntityComment",
* mappedBy="games"
* )
*/
protected $comments;
在Twig中,我使用这个:
{{ game.comments.id }}
我的错误在哪里?
game.comments
返回一个集合,集合没有ID。您必须遍历Collection并获取每个Comment的ID:
{% for comment in game.comments %}
{{ comment.id }}
{% endfor %}
尝试在game.comments
和game.comments[0]
上使用dump()
来了解我的意思。
您可以在树枝配置中设置strict_variables: false这修复了我的问题