原则:OneToOne 的级联持续不保留关联数据

Doctrine: Cascade persists for OneToOne does not persist associated data

提问人:floriank 提问时间:11/12/2023 更新时间:11/12/2023 访问量:25

问:

我正在尝试将新用户与用户配置文件一起保存,由于某种原因,仅保存了用户记录,但根本没有保存用户配置文件。老实说,我很难理解如何正确配置关联。我很确定单侧或双侧的 OneToOne 配置有问题,但我无法弄清楚是什么。

控制器(节选)

        if ($form->isSubmitted()) {
            if (!$form->isValid()) {
                dd($form->getErrors(true));
            }

            $user = $form->getData()['user'];
            $userProfile = $form->getData()['userProfile'];

            // Hash the password (based on the security.yaml config for the $user class)
            $hashedPassword = $passwordHasher->hashPassword(
                $user,
                $user->getPassword()
            );
            $user->setPassword($hashedPassword);

            $user->setProfile($form->getData()['userProfile']);
            $userProfile->setUser($user);

            $entityManager->persist($user);
            $entityManager->flush();
            dd('PERSISTED');
        }

用户实体(摘录)

    #[ORM\Id]
    #[ORM\Column(type: 'uuid', unique: true)]
    #[ORM\GeneratedValue(strategy: 'CUSTOM')]
    #[ORM\CustomIdGenerator(class: UuidGenerator::class)]
    private ?string $userId = null;

    #[OneToOne(targetEntity: UserProfile::class, mappedBy: 'profile', cascade: ['all'])]
    private UserProfile $profile;

用户配置文件实体(摘录)

    #[ORM\Id]
    #[ORM\Column(type: 'uuid', unique: true)]
    #[ORM\GeneratedValue(strategy: 'CUSTOM')]
    #[ORM\CustomIdGenerator(class: UuidGenerator::class)]
    private ?string $userProfileId = null;

    #[OneToOne(targetEntity: User::class, inversedBy: 'profile', cascade: ['all'])]
    #[JoinColumn(name: 'userId', referencedColumnName: 'userId')]
    private User $user;

    #[ORM\Column(type: Types::GUID)]
    #[ORM\JoinColumn(nullable: false)]
    private ?string $userId = null;
PHP symfony 说-ORM学说

评论

1赞 Kevin Kopf 11/12/2023
我怀疑它的目的是创造一个无休止的循环,因为 and have 和 doctrine 都试图立即打破它。只是一种预感,教义是一个凌乱的黑匣子......尝试从配置文件实体中删除级联规则,看看我是否正确。如果我是,我会发布这个作为答案。UserUserProfilecascade=all
0赞 floriank 11/12/2023
不,它没有解决问题。是的,我也开始有那种黑洞的感觉。
0赞 Kevin Kopf 11/12/2023
奇怪。。。我迅速检查了教义代码,它似乎正在做它应该做的事情。您确定您的数据库与实体类是最新的吗?
1赞 Will B. 11/12/2023
它是什么样子的?User::setProfile()UserProfile::setUser()
2赞 Jakumi 11/13/2023
到目前为止看起来是正确的,有一件事可能是问题所在:您省略了 from 和(在两个实体上)。这些可能是必需的,除非你有正确的使用子句。这只是黑暗中的一刀,可能无关紧要。ORM\OneToOneJoinColumn

答: 暂无答案