集合类型新添加的元素关系为null



我有一个包含许多学生实体的实体教室,一个学生只属于一个教室

my classroom form:

$builder
->add('name')
->add('students', CollectionType::class, [
'entry_type' => StudentType::class,
'allow_add' => true,
'allow_delete' => true,
])
;

当添加新学生时,教室学生集合具有新添加的学生,而新学生字段教室为NULL,我在教室实体上添加了事件级联持久性

@ORMOneToMany(targetEntity=Student::class, mappedBy="classroom", orphanRemoval=true, cascade={"persist"})

但我仍然得到错误的教室字段在新的学生是NULL

Column 'classroom_id' cannot be null

有人知道为什么吗?

实际上symfont不调用你的方法addStudent,因为选项by_reference默认有true,所以要强制symfony使用你的方法,你必须将by_reference设置为false

->add('students', CollectionType::class, [
'entry_type' => StudentType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
])