我從早上開始就一直在嘗試解決一個問題,但我無法弄清楚。我正在開發一個使用 Symfony 6 和 PHP 8.0 的專案。
我在學生和成績之間有一個 OneToMany 連接 - > 每個學生可以有許多成績物件。每個年級與一名學生有關。
但是在 Grade 物體中,我在 Grade 和 Course 之間也有一個 ManyToOne 鏈接 -> 每個 Grade 都與一個 Course 相關。每個 Course 可以有多個 Grade 物件。
當我(從學生表中)洗掉學生的成績時,在成績表中我遇到了這樣的行為:學生 ID 被洗掉,但課程 ID 仍然存在。我希望洗掉成績表中的整個條目。
我試圖orphanRemove = true從學生表中添加成績屬性,情況更糟。該課程的所有成績都將被洗掉,包括該課程。我可以理解為什么會這樣。這是因為我將 Grade 鏈接到 Student 類和 Course 類,我遇到了這個問題:
當使用 orphanRemoval=true 選項時,Doctrine 假設物體是私有的,不會被其他物體重用。如果您忽略此假設,即使您將孤立物體分配給另一個物體,您的物體也會被 Doctrine 洗掉
我想知道如何解決這個問題。創建一個 cron 作業以洗掉所有帶有student_id = null的成績是一個好的解決方案還是有更好的選擇?
class Student extends AbstractUser
{
#[ORM\OneToMany(mappedBy: 'student', targetEntity: Grade::class, cascade: ['persist', 'remove'])]
protected Collection $grades;
}
class Grade {
#[ORM\ManyToOne(targetEntity: Student::class, inversedBy: 'grades')]
protected ?Student $student;
#[ORM\ManyToOne(targetEntity: Course::class, cascade: ['persist', 'remove'], inversedBy: 'grades')]
protected ?Course $course;
}
class Course {
#[ORM\OneToMany(mappedBy: 'course', targetEntity: Grade::class, cascade: ['persist', 'remove'], orphanRemoval: true)]
protected Collection $grades;
}
我還嘗試添加nullable = false,例如:
#[
ORM\ManyToOne(targetEntity: Student::class, inversedBy: 'grades'),
ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')
]
protected ?Student $student;
#[
ORM\ManyToOne(targetEntity: Course::class, inversedBy: 'grades'),
ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')
]
protected ?Course $course;
我對邏輯錯誤感到震驚執行查詢時發生例外:SQLSTATE [23000]:完整性約束違規:1048列'student_id'不能為空
我想指定我使用 EasyAdmin 4.0 來執行此操作。在 StudentCrudController 中,我的 Grades 屬性如下所示:
CollectionField::new('grades')
->setEntryType(GradeType::class)
->setEntryIsComplex(),
uj5u.com熱心網友回復:
從 中洗掉cascade引數Grade::course,因為如果您洗掉成績,則屬于它的課程和成績將被洗掉
class Student extends AbstractUser
{
#[ORM\OneToMany(mappedBy: 'student', targetEntity: Grade::class, cascade: ['persist', 'remove'])]
protected Collection $grades;
}
class Grade {
#[
ORM\ManyToOne(targetEntity: Student::class, inversedBy: 'grades'),
ORM\JoinColumn(nullable: false, onDelete: 'CASCADE'),
]
protected ?Student $student;
#[
ORM\ManyToOne(targetEntity: Course::class, inversedBy: 'grades'),
ORM\JoinColumn(nullable: false, onDelete: 'CASCADE'),
]
protected ?Course $course;
}
您也可以添加orphanRemove = true到Student::grades
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/513427.html
下一篇:多個CORS標頭“Access-Control-Allow-Origin”不允許使用usginreact、symfony和docker
