Symfony 2多对多sql转换为dql

时间:2015-02-16 14:57:45

标签: sql symfony doctrine dql

我在绘制以前从未遇到过的多对多关系时遇到了问题。我有两个实体文档,考试和关系多对多document2exam。

信息:

实体/ Document.php, class Document {

private $id;
private $entryNumber;
private $isPaymentFree;
private $profile;
private $dateCreated;
private $dateModified;
private $exams;
private $invoice;

}

实体/ Exam.php

课程考试{

private $name;
private $examCode;
private $dateTime;
private $startOnlineRegDate;
private $endOnlineRegDate;
private $endChangeDate;
private $session;
private $link;
private $documents;
private $isWriting;
private $examService;

}

资源/ Document.orm.xml

    <many-to-many field="exams" inversed-by="documents" target-entity="\Entity\Exam">
        <join-table name="document2exam">
            <join-columns>
                <join-column name="document_id" referenced-column-name="id" nullable="false" on-update="CASCADE" on-delete="CASCADE" />
            </join-columns>
            <inverse-join-columns>
                <join-column name="exam_id" referenced-column-name="id" nullable="false" on-update="CASCADE" on-delete="CASCADE" />
            </inverse-join-columns>
        </join-table>
        <cascade>
            <cascade-all />
        </cascade>
    </many-to-many>

资源/ Exam.orm.xml

    <many-to-many field="documents" mapped-by="exams" target-entity="\Entity\Document" />

我的SQL是:

SELECT en.entry_number, en.exam_id 
FROM Data_ExamNotes en 
WHERE exam_id = 3 
    AND en.entry_number NOT IN ( 
        SELECT d.entry_number
        FROM Document d
            INNER JOIN document2exam d2e ON d.id = d2e.document_id
        WHERE d2e.exam_id = 3 
            AND d.entry_number is not null
    )
ORDER BY en.entry_number ASC

由于document2exam表,我无法编写dql查询。

谢谢你,对不起我的语言:)

1 个答案:

答案 0 :(得分:0)

我找到了问题的答案。

$em = $this->getEntityManager();

        $query = $em->createQuery(
            "SELECT en.entryNumber as enNum, IDENTITY(en.exam) as ex
                FROM UcictDataBundle:ExamNotes en 
                WHERE en.exam = :exam 
                    AND en.entryNumber NOT IN (
                        SELECT d.entryNumber
                        FROM UcictStudentBundle:Document d
                            INNER JOIN d.exams e
                        WHERE e.id = :exam 
                            AND d.entryNumber is not null                   
                    )
                ORDER BY en.entryNumber ASC");

        $ret = $query
               ->setParameter('exam', $exam)
               ->getResult();
        return $ret;