【问题标题】:Get entities from a unidirectional many to many relation with Doctrine2 and Symfony2使用 Doctrine2 和 Symfony2 从单向多对多关系中获取实体
【发布时间】:2013-05-22 11:03:29
【问题描述】:

我目前正在开展一个语言评估项目,该项目使您能够以您想要的语言参加考试并评估您的水平。我使用 Symfony2 框架,也使用 Doctrine2。我的问题是以下一个:

我有两个由多对多关系链接的实体考试和问题(考试是所有者)。每个考试可以关联多个问题,每个问题可以关联多个考试。

这是我的代码:

考试实体

/**
 * Exam
 *
 * @ORM\Table(name="cids_exam")
 * @ORM\Entity(repositoryClass="LA\AdminBundle\Entity\ExamRepository")
 */
class Exam
{
    ...

    /**
    * @ORM\ManyToMany(targetEntity="LA\AdminBundle\Entity\Question", cascade={"persist"})
    * @ORM\JoinTable(name="cids_exam_question")
    */
    private $questions;

    ...


    /**
     * Constructor
     */
    public function __construct()
    {
        $this->questions = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add questions
     *
     * @param \LA\AdminBundle\Entity\Question $questions
     * @return Exam
     */
    public function addQuestion(\LA\AdminBundle\Entity\Question $questions)
    {
        $this->questions[] = $questions;

        return $this;
    }

    /**
     * Remove questions
     *
     * @param \LA\AdminBundle\Entity\Question $questions
     */
    public function removeQuestion(\LA\AdminBundle\Entity\Question $questions)
    {
        $this->questions->removeElement($questions);
    }

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

只要是单向关系,我的 Question 类中就没有“exams”属性。

现在,我要做的是获取与特定考试相关的所有问题,调用 getQuestions() 方法,如下所示:

$questions = $exam->getQuestions();

但是这个方法返回一个空数组,即使我的数据库中有数据。如果我 var_dump $exam 变量,我可以看到问题数组是空的:

object(LA\AdminBundle\Entity\Exam)[47]
  private 'id' => int 5
  ...
  private 'questions' => 
    object(Doctrine\ORM\PersistentCollection)[248]
      private 'snapshot' => 
        array (size=0)
          empty
      private 'owner' => null
      private 'association' => null
      private 'em' => null
      private 'backRefFieldName' => null
      private 'typeClass' => null
      private 'isDirty' => boolean false
      private 'initialized' => boolean false
      private 'coll' => 
        object(Doctrine\Common\Collections\ArrayCollection)[249]
          private '_elements' => 
            array (size=0)
              ...

我想我可以在我的 QuestionRepository 中编写一个 findByExam() 函数,但我真的不知道在这种情况下如何实现连接。

任何帮助都会很棒!

【问题讨论】:

    标签: symfony doctrine-orm many-to-many


    【解决方案1】:

    要在 QuestionRepository 中使用 findByExam() 方法,请执行以下操作:

     public function findByExam($exam)
     {
        $q = $this->createQueryBuilder('q')
            ->where('q.exam = :exam')
            ->setParameter('exam', $exam)
            ->getQuery();
    
        return $q->getResult();
     }
    

    您还可以创建双向关系而不是单向关系!

    每门考试可以与几个问题相关,每个问题都可以 与几门考试有关。

    通过将其添加到您的问题实体来创建双向关系:

    use Doctrine\Common\Collections\Collection;
    use Doctrine\Common\Collections\ArrayCollection;
    use Vendor\YourExamBundle\Entity\ExamInterface;
    
    class Question 
    {
        protected $exams;
    
        public function __construct()
        {
           $this->exams = new ArrayCollection();
        }
    
        public function getExams()
        {
           return $this->exams;
        }
    
        public function addExam(ExamInterface $exam)
        {
            if !($this->exams->contains($exam)) {
                $this->exams->add($exam);
            }
            return $this;
        }
    
        public function setExams(Collection $exams)
        {
            $this->exams = $exams;
    
            return $this;
        }
    
        // ...
    

    之后你可以使用...

    $question->getExams()
    

    ... 在您的控制器中。

    要自动加入你的相关实体,学说的 fetch 选项可以用于:

    • LAZY(访问时加载关系)
    • EAGER(自动加入关系)
    • EXTRA_LAZY(手动提取)

    示例:

    /**
     * @ManyToMany(targetEntity="Question",inversedBy="exams", cascade={"all"}, fetch="EAGER")
     */
    

    虽然急切加载在性能方面存在缺点,但它可能是您的一个选择。

    使用 EAGER 获取学说

    每当您查询具有持久关联的实体时, 这些关联被映射为 EAGER,它们将自动 与被查询的实体一起加载,因此立即 可用于您的应用程序。

    在Doctrine Documentation 中了解更多信息。

    使用关系时应检查的另一个选项是 cascade 选项。

    请参阅文档的Doctrine - Working with Associations 章节。

    提示: 您应该为考试和问题创建接口并使用它们而不是您集合中的原始实体,并添加方法以便更轻松地扩展。

    【讨论】:

    • 感谢您的精彩回答!这将有很大帮助。如果我解决了我的问题或遇到了其他问题,我会继续努力的;)
    • 我尝试创建双向关系而不是单向关系,但仍然无法获得任何东西。在将考试及其相关问题存入数据库之前,您认为这可能是控制器中的问题吗?我可能必须将每个问题实际添加到考试实例中?我的意思是你知道表单中的绑定请求是否会调用 addQuestion() 函数还是我必须手动执行?
    • 搜索了几个小时后,我意识到我的问题根本不是来自多对多关系,而是来自其他干扰它的东西。实际上,我的考试实体中的 getQuestions() 函数有效,这是实现我想要的最佳方式,具有单向关系。感谢您的帮助,我使用了您对 add 函数的建议,并且也很好地查看了 Doctrine Fetching。
    • 我很高兴能提供帮助 - 询问您的原始问题,以便在存储库(已涵盖)中创建一个 findExam 方法并获取您可能想要接受我的答案的相关实体。那么它可能对其他人有帮助:)
    • @Beliasus,你能和我们分享一下最终解决了你的问题吗?我有同样的问题,你说“[...],我意识到我的问题根本不是来自多对多关系,而是来自其他干扰它的东西”。什么是“别的东西”?谢谢!
    【解决方案2】:

    使用 Doctrine2 ORM 与关联表exam_questions 的双向关系 考试id question_id

    <?php
    
    class Exams
    
     ....OTHER PROPERTIES...
    
     /**
      * Owning Side
      *
      * @ManyToMany(targetEntity="Questions", inversedBy="exams")
      * @JoinTable(name="exam_questions",
      *      joinColumns={@JoinColumn(name="exam_id", referencedColumnName="id")},
      *      inverseJoinColumns={@JoinColumn(name="question_id", referencedColumnName="id")}
      *      )
      */
     private $questions;
    
     ..OTHER CODES..
    
     }
    
    
     class Questions{
    
    
     ..OTHER CODES..
    
     /**
      * Inverse Side
      *
      * @ManyToMany(targetEntity="Exams", mappedBy="questions")
      */
     private $exams;
    
     ..OTHER CODES..
    
     }
    

    http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-manytomany

    【讨论】:

    • 链接的引用不存在(不再存在)
    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2015-12-12
    相关资源
    最近更新 更多