我在两个字段 personnelLanguages(类Personnel)和人员(类LanguagesPersonnel)之间建立了关系OneToMany,问题是在插入中我有字段personnel_id = personnel_languages表中的NULL:
id personnel_id level language
7 NULL 5 5
8 NULL 5 1
实体:
人员实体:
/**
* Personnel
*
* @ORM\Table(name="personnel")
* @ORM\Entity(repositoryClass="HomeBundle\Repository\PersonnelRepository")
*/
class Personnel
{
// some fields
/**
* @var collection
* @ORM\OneToMany(targetEntity="PersonnelLanguages" , mappedBy="personnel" , cascade={"all"})
*/
private $personnelLanguages;
public function __construct()
{
$this->personnelLanguages = new ArrayCollection(array(new PersonnelLanguages(),new PersonnelLanguages()) );
}
// getters and setters
/**
* @return collection
*/
public function getPersonnelLanguages()
{
return $this->personnelLanguages;
}
/**
* @param collection $personnelLanguages
*
* @return self
*/
public function setPersonnelLanguages(collection $personnelLanguages)
{
$this->personnelLanguages = $personnelLanguages;
return $this;
}
}
PersonnelLanguages实体:
/**
* PersonnelLanguages
*
* @ORM\Table(name="personnel_languages")
* @ORM\Entity(repositoryClass="HomeBundle\Repository\PersonnelLanguagesRepository")
*/
class PersonnelLanguages{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var int
*
* @ORM\ManyToOne(targetEntity="Personnel", inversedBy="personnelLanguages")
* @ORM\JoinColumn(name="personnel_id", referencedColumnName="id")
*/
private $personnel;
/**
* @var string
*
* @ORM\Column(name="language", type="string", length=50, nullable=true)
*/
private $language;
/**
* @var string
*
* @ORM\Column(name="level", type="string", length=50, nullable=true)
*/
private $level;
// getters and setters
}
**表格**:
PersonnelType:
->add("personnelLanguages",CollectionType::class, array(
'entry_type' => PersonnelLanguagesType::class,
'entry_options' => array("label"=>false),
'allow_add' => true,
'allow_delete' => true,
))
因此,当我创建一个包含personnelLanguages字段的新Personnel时,我在employees_languages表中为personnel_id设置了NULL值。
一个想法:可能因为在创建的那一刻,personnel_id不存在!!!
调试:
我调试了这个动作,我发现这两个 print_r ,人员对象中的 id 不存在,直到 die
教条应该自动管理这个问题还是我的代码有问题?
public function newAction(Request $request)
{
$personnel = new Personnel();
$form = $this->createForm('HomeBundle\Form\PersonnelType', $personnel);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
print_r($personnel->getId()); echo "--";
print_r($personnel->getpersonnelLanguages()); die;
$em = $this->getDoctrine()->getManager();
$em->persist($personnel);
$em->flush();
return $this->redirectToRoute('personnel_show', array('id' => $personnel->getId()));
}