Php 如何使用symfony原则从多对多关系中删除单个记录?

Php 如何使用symfony原则从多对多关系中删除单个记录?,php,symfony,model-view-controller,doctrine,Php,Symfony,Model View Controller,Doctrine,下面是包含函数的两个类 班级与学生班级之间存在着多对多的关系 class Section { /** * @ORM\ManyTOMany(targetEntity="Student",inversedBy="sections") */ private $students; public function __construct() { $this->students = new ArrayCollection()

下面是包含函数的两个类 班级与学生班级之间存在着多对多的关系

class Section
{       
    /**
     * @ORM\ManyTOMany(targetEntity="Student",inversedBy="sections")
     */ 
    private $students;

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

    /**
     * Add students
     *
     * @param \Blogger\sectionBundle\Entity\Student $students
     * @return Section
     */
    public function addStudent(\Blogger\sectionBundle\Entity\Student $students)
    {
        $this->students[] = $students;

        return $this;
    }

    /**
     * Remove students
     *
     * @param \Blogger\sectionBundle\Entity\Student $students
     */
    public function removeStudent(\Blogger\sectionBundle\Entity\Student $students)
    {
        $this->students->removeElement($students);
    }

    /**
     * Get students
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getStudents()
    {
        return $this->students;
    }
}

就像mysql一样

从学生组删除 where student\u id=从student where student.name=dummy中选择student.id 和截面_id=1 有什么问题吗

public function removeStudent(Student $student)
{
    $this->students->removeElement($student);
}

您可以使用通用条令命令生成getter和setter

app/console doctrine:generate:entities NameSpace:Entity
此外,您还应该了解如何将许多双向关系与条令同步。您可以阅读有关加法器的内容,但相同的逻辑适用于remove方法

编辑-问题更新后

如果我正确理解了您的意思,那么当您有学生姓名时,您希望从部分中删除一名学生。创建的student_部分是根据Doctrine生成的表。您可以在控制器或存储库中执行正常的PDO语句,但我会在模型中个人化地实现一个函数,使其尽可能保持OOP

public function removeStudentByName(Student $student)
{
    $toRemove = $this->students->filter(function (Student $s) use ($student) {
        return ($->getName() == $student->getname());
    });

    foreach ($toRemove as $student) {
        $this->students->remove($student);
    }

}
在控制器中,您可以执行以下操作:

//$student, $em is fetched
$section->removeStudentByName($student);
$em->flush();

对不起,我的问题有误导性且不清楚 我找到了我要找的东西

//in the controller:
    $section = $em->getRepository('BloggersectionBundle:Section')->find(2);
    $student = $em->getRepository('BloggersectionBundle:Student')->findByStudentId("555555");
    $student->removeSections($section);
    $em->flush();
在学生模型中

public function removeSections(Section $sections)
    {   
        $sections->removeStudent($this);
        $this->sections->removeElement($sections);
    }
最后,我编辑了《学生》和《学生》两个部分 级联删除

 * @ORM\ManyToMany(targetEntity="Section", mappedBy="students", cascade={"persist", "remove"})

嗨,答案是在低质量的帖子里。请您添加一行解释来提升它。getter和setter已经添加到我的类@Stiven LIupaThan中,您必须实现同步。逻辑与条令的官方文档相同,您应该设置在控制器、服务等@HatemTito中使用它
 * @ORM\ManyToMany(targetEntity="Section", mappedBy="students", cascade={"persist", "remove"})