学说多对多单向关系增加了集合

时间:2018-07-09 11:41:48

标签: php symfony doctrine-orm doctrine symfony-2.8

我有一个User实体,与EventPricing实体具有多对多关系。与连接表的关系是单向的,如下所示:

<many-to-many field="eventsPricing" target-entity="App\TagBundle\Entity\EventPricing" orphan-removal="true" fetch="EAGER">
    <join-table name="app_user_events_pricing">
        <join-columns>
            <join-column name="user_id" referenced-column-name="id" unique="false"/>
        </join-columns>
        <inverse-join-columns>
            <join-column name="event_pricing_id" referenced-column-name="id" unique="false"/>
        </inverse-join-columns>
    </join-table>
    <cascade>
        <cascade-all/>
    </cascade>
</many-to-many>

此外,我有一条命令,我想以编程方式添加eventPricings,但是在循环中的第一个用户之后我却以某种方式获得了NullPointerException。通常我会分批执行此操作(结果相同),但是为了简单起见,我在此处对整个集执行flush()。代码如下:

/**
 * @param InputInterface $input
 * @param OutputInterface $output
 * @return int|null|void
 */
protected function execute(InputInterface $input, OutputInterface $output)
{

    $em = $this->getContainer()->get('doctrine.orm.default_entity_manager');

    $userRepo = $em->getRepository(User::class);
    $users = $userRepo->findToAddEventPricing();

    /** @var User $user */
    foreach ($users as $index => $user) {

        $output->writeln(sprintf('Adding prices for User with id %s', $user->getId()));

        /** @var ArrayCollection $relatedEventTypes */
        $relatedEventTypes = $user->getRelatedEventTypes();

        if ($relatedEventTypes) {

            foreach ($relatedEventTypes as $relatedEventType) {

                $pricing = new EventPricing();
                $pricing->setEvent($relatedEventType);
                $pricing->setPrice(null);

                $user->addEventsPricing($pricing);
            }

            $user->setShowEventPrices(true);
        }

        $em->persist($user);
    }

    $em->flush();

    $output->writeln('Done..');
}

不确定发生了什么,但是我认为这与学说如何管理对象有关。由于cascade操作已设置,相关实体已正确保存,所以我根本没有填写联接表。

任何建议都非常感谢!

0 个答案:

没有答案