Doctrine ManytoOne ArrayCollection 只填充一个值

Doctrine ManytoOne ArrayCollection only populated with one value

我在两个实体中定义了一个 ArrayCollection 关系:

/**
 * User
 *
 * @ORM\Table(name="users", uniqueConstraints= {@ORM\UniqueConstraint(name="email_UNIQUE", columns={"email"})}, indexes={@ORM\Index(name="email_id", columns={"id_user", "email"})})
 * @ORM\Entity
 */

class User
{
/**
 * @ORM\ManyToOne(targetEntity="App\Entities\Usercharts", inversedBy="charts")
 * @ORM\JoinColumn(name="id_user", referencedColumnName="id_user")
 */
private $userscharts;

/**
 * Useritems
 *
 * @ORM\Table(name="useritems", indexes={@ORM\Index(name="userid", columns={"id_user"}), @ORM\Index(name="chartno", columns={"chart_no"})})
 * @ORM\Entity
 */
class Usercharts
{

/**
 * @ORM\OneToMany(targetEntity="App\Entities\User", mappedBy="userscharts")
 *
 */
private $charts;


public function __construct()
{
    $this->charts = new ArrayCollection();
}

usercharts的数据结构:

问题是 ArrayCollection 只填充了一个值,似乎是填充的最后一项 table;例如对于此数据,

'1201','4769'
'1202','4769'
'1400','4769'
'1434','4769'
'1435','4769'
'1510','4769'
'2000','4769'
'2050','4769'
'3726','4769'
'3808','4769'
'7950','4769'

模板twig中的ArrayCollection $charts值returns只有7950

    <ul>
        {% for chart in user.userscharts %}
            <li>{{ chart.chartno }}</li>
        {% endfor %}
    </ul>

我也尝试为 chart_no 添加主键标识符(这似乎很有意义):

    /**
     * @var integer
     * @ORM\Id
     * @ORM\Column(name="chart_no", type="integer", nullable=false)
     */
    private $chartno = '';

但这会导致

OutOfBoundsException.php line 40
at OutOfBoundsException::missingPrimaryKeyValue('App\Entities\Usercharts', 'chartno') in AbstractProxyFactory.php line 125
at AbstractProxyFactory->getProxy('App\Entities\Usercharts', array('userid' => '4769')) in UnitOfWork.php line 2698

如何正确修改实体学说声明以获得完整的图表数组?

您的关联类型不正确。一个用户可以有多个图表,因此 $userscharts 的关联应该是 OneToMany$charts

的关联应该是 ManyToOne
class User
{
/**
 * @ORM\OneToMany(targetEntity="App\Entities\Usercharts", mappedBy="user")
 */
private $userscharts;

public function __construct()
{
    $this->userscharts = new ArrayCollection();
}
.....

class Usercharts
{

/**
 * @ORM\ManyToOne(targetEntity="App\Entities\User", inversedBy="userscharts")
 * @ORM\JoinColumn(name="id_user", referencedColumnName="id_user")
 */
private $user;