我有一个Symfony 4.2应用程序。有实体游戏和GameGenre。他们彼此之间有ManyToMany关系。我正在尝试加载灯具并收到以下错误:
在类“ App \ Entity \ GameGenre”中无法确定属性“ games”的访问类型:在类“ App \ Entity \ GameGenre”中的属性“ games”可以使用方法“ addGame()”,“ removeGame()”,但新值必须是\ Traversable的数组或实例,并指定了“ App \ Entity \ Game”。
我的代码如下。
Game.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity(repositoryClass="App\Repository\GameRepository")
*/
class Game
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
...
/**
* @ORM\ManyToMany(
* targetEntity="App\Entity\GameGenre",
* inversedBy="games"
* )
*/
private $genres;
...
/**
* @return Collection|GameGenre[]
*/
public function getGenres() : Collection
{
return $this->genres;
}
public function addGenre(GameGenre $genre): self
{
if (!$this->genres->contains($genre)) {
$this->genres[] = $genre;
$genre->addGame($this);
}
return $this;
}
public function removeGenre(GameGenre $genre): self
{
if ($this->genres->contains($genre)) {
$this->genres->removeElement($genre);
$genre->removeGame($this);
}
return $this;
}
...
public function __construct()
{
$this->genres = new ArrayCollection();
}
}
GameGenre.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity(repositoryClass="App\Repository\GameGenreRepository")
*/
class GameGenre
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\ManyToMany(
* targetEntity="App\Entity\Game",
* mappedBy="genres"
* )
* @ORM\OrderBy({"name" = "ASC"})
*/
private $games;
...
/**
* @return Collection|Game[]
*/
public function getGames() : Collection
{
return $this->games;
}
public function addGame(Game $game): self
{
if (!$this->games->contains($game)) {
$this->games[] = $game;
$game->addGenre($this);
}
return $this;
}
public function removeGame(Game $game): self
{
if ($this->games->contains($game)) {
$this->games->removeElement($game);
$game->removeGenre($this);
}
return $this;
}
public function __construct()
{
$this->games = new ArrayCollection();
}
}
看起来装置装置Yamls并没有什么奇怪的地方:
genre.yaml
App\Entity\GameGenre:
genre_{1..9}:
...
games: '@game_*'
game.yaml 没有提及流派字段,但是我试图通过调用addGenre()而不是addGame()来改变关系方面,或者我在两个灯具文件中都使用了它们,但是没有帮助,所以我认为还有其他问题。
能请你帮我吗?
答案 0 :(得分:1)
您的字段是一个数组,但是您尝试插入一个值,它应该是:
App\Entity\GameGenre:
genre_{1..9}:
...
games: ['@game_*']
或
App\Entity\GameGenre:
genre_{1..9}:
...
games:
- '@game_*'