我正在Fixtures
使用 Doctrine 在 Symfony2 中创建一些。我收到以下错误:
Integrity constraint violation: 1062 Duplicate entry '206-411' for key 'PRIMARY'
当我尝试保持多对多单向关联时。
我理解这个错误,但我很困惑:在多对多关系中某些 ID 是重复的不是很明显吗?
如果我错了,请纠正我。我把我的代码放在下面,欢迎任何澄清。
夹具文件:
namespace sociaLecomps\SuperBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\Query;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadAssociationsData extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
private $container;
public function setContainer(ContainerInterface $container = null){
$this->container = $container;
}
public function load(ObjectManager $manager)
{
$em = $this->container->get('doctrine')->getManager('default');
/*
* COURSE - STUDENT ASSOCIATION
*/
$courses = $em->createQuery('SELECT c FROM sociaLecompsSuperBundle:Course c')->getResult();
$students = $em->createQuery('SELECT s FROM sociaLecompsSuperBundle:Student s')->getResult();
$i=0;
for($j=0; $j<count($courses); $j++){
$course = $courses[$j];
//here I'm adding two different students to the same course
$s = array($students[$i], $students[$i++]);
$course->setSubscribedStudents($s);
$em->persist($course);
$i++;
}
$manager->flush();
}
}
Course类中的关系声明:
/**
* @ORM\ManyToMany(targetEntity="Student")
* @ORM\JoinTable(name="relation_course_student",
* joinColumns={@ORM\JoinColumn(name="course_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="student_id", referencedColumnName="id")}
* )
**/
private $subscribed_students;
public function __construct() {
$this->subscribed_students = new ArrayCollection();
}
Fixtures
在尝试创建关联之前,也使用 来创建实体 Student 和 Course 。
如果我尝试在每门课程中只插入一名学生,一切都会顺利进行。