教义一对多级联持续存在,外键为空

syl*_*ain 5 php doctrine symfony

我知道 SA 中有几个关于此的主题,但我不明白为什么我的代码不起作用......让我解释一下:

我有一个公司实体,可能有许多相关用户。当我创建公司时,我想使用相同的表单创建一个“admin”用户(第一个用户)。

我的实体:

class Company
{
    **
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
    */
    private $id;
    ...

    /**
     * A company has many users.
     * @ORM\OneToMany(targetEntity="User", mappedBy="company", cascade={"persist"})
     */
    private $users;
    ...

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

    public function addUser(User $user)
    {
        $user->setCompany($this);
        $this->users->add($user);
        return $this; // doesn't appear in the documentation but found in SA... doesn't change anything
    }

    public function removeUser(User $user)
    {
        // ...
    }

}


class User
{
    **
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
    */
    private $id;
    ...

    /**
     * Many users belong to a company.
     * @ORM\ManyToOne(targetEntity="Company", inversedBy="users")
     * @ORM\JoinColumn(name="company_id", referencedColumnName="id")
     */
    private $company;
    ...

    /**
     * @param mixed $company
     */
    public function setCompany ($company)
    {
        $this->company = $company;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我提交表单(其中包含用于创建公司和第一个用户的字段)时,公司以及第一个用户都保存在数据库中,但用户的company_id设置为NULL。我必须这样做才能使其正常工作(下面的代码位于专门用于管理公司的服务中):

public function createCompany($company)
    {
    ...
    $company->getUsers()->get(0)->setCompany($company); // <- HERE (btw is there a way to access the first user without using get(0) ?)
    ...

    $this->entityManager->persist($company);
    $this->entityManager->flush();
    }
Run Code Online (Sandbox Code Playgroud)

我不应该那样做,对吗?我以为

$user->setCompany($this); 
Run Code Online (Sandbox Code Playgroud)

在 addUser 中会自动执行...

我哪里错了?

编辑 :

公司表格:(再次,我没有放置所有代码以使其清晰,我只是发布有用的行):

class RegisterCompanyForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('name',null,[
            'translation_domain' => 'forms',
            'label' => 'register_company.name.label'
        ])
        ...
        ->add('users', CollectionType::class, [
            'entry_type' => RegisterUserForm::class,
            'entry_options' => array('label' => false),
            'allow_add' => true,
            'by_reference' => false,    
        ])
        ; 
    }
}
Run Code Online (Sandbox Code Playgroud)

用户表格

class RegisterUserForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('givenName',TextType::class,[
            'translation_domain' => 'forms',
            'label' => 'register_user.givenName.label'
        ])
        ->add('familyName',null,[
            'translation_domain' => 'forms',
            'label' => 'register_user.familyName.label'
        ])
        ...
        ->add('password',null,[
            'translation_domain' => 'forms',
            'label' => 'register_user.password.label'
        ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'App\Entity\User',
        ));
    }
}
Run Code Online (Sandbox Code Playgroud)

我的表单树枝模板:

{% extends 'layout/layout.html.twig' %}
{% trans_default_domain 'ui' %}

{% block title %}My Form {% endblock %}

{% block content %}
    <div class="container">
        <div class="starter-template">
            <h1>{% trans %}title.register{% endtrans %}</h1>
            {{ form_start(form) }}
            {{ form_errors(form) }}
            {{ form_row(form.name) }}
            ...
            {% for user in form.users %}
            {{ form_row(user.givenName) }}
            {{ form_row(user.familyName) }}
            ...
            {{ form_row(user.password) }}
            {% endfor %}
            {{ form_end(form) }}
        </div>
    </div>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

控制器:

class CompanyController extends Controller
{
    public function inscription(CompanyManager $companyManager, Request 
$request)
    {
        $company = new Company();      
        $user = new User();
        $company->getUsers()->add($user);
        $form = $this->createForm(RegisterCompanyForm::class, $company);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // saving to DB is managed by a service
            $companyManager->createCompany($company);
        }

        return $this->render('views/company/register.html.twig', [
                'form'  => $form->createView()
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

在CompanyManager服务中:

public function createCompany($company)
    {

        // i'd like to avoid the next line !!! because i think it shouldn't be there...
        $company->getUsers()->get(0)->setCompany($company);

        $this->entityManager->persist($company);
        $this->entityManager->flush();
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我按照本指南创建了我的表单:https ://symfony.com/doc/master/form/form_collections.html

syl*_*ain 1

嗯,其实答案已经很明显了……

错误发生在CompanyController中:

$company = new Company();      
$user = new User();
$company->getUsers()->add($user);
Run Code Online (Sandbox Code Playgroud)

应该 :

$company = new Company();      
$user = new User();
$company->addUser($user);
Run Code Online (Sandbox Code Playgroud)

在原始代码中:

$user->setCompany($this);
Run Code Online (Sandbox Code Playgroud)

从未使用过,因为我“手动”将用户添加到集合中...因此创建的用户和公司之间的链接从未设置。我错了,因为我遵循的教程(https://symfony.com/doc/master/form/form_collections.html)略有不同......