所以,我试图显示属于游戏的所有评论,但出于某种原因,我总是得到这个错误:
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;
游戏实体:
/**
* Comments array
*
* @ORM\OneToMany(
* targetEntity="AppBundle\Entity\Comment",
* mappedBy="games"
* )
*/
protected $comments;
在Twig我用这个:
{{ game.comments.id }}
我的错误在哪里?
答案 0 :(得分:3)
game.comments
正在返回一个Collection,而一个集合没有ID。您必须遍历Collection并获取每个Comment的ID:
{% for comment in game.comments %}
{{ comment.id }}
{% endfor %}
尝试在dump()
和game.comments
上使用game.comments[0]
查看我的意思。